0

I have the following object

public class Error
{
    public long id { get; set; }
    public string code { get; set; }
    public string message { get; set; }
    public long qty{ get; set; }

}

public class RootObject
{
    public List<Error> error { get; set; }
}

my Json result is like this

{"error":[{"id":"15006","code":"Error CODE","message":"Error Message","qty":""}]}

and I map the json string to my object like this

RootObject obj =JsonConvert.DeserializeObject<RootObject>(jsonString);

My question is the id and qty fields. The json result wraps the id and qty in quotes making it a string but I want this to be a long datatype. I need this as I'm using a library to export this data to Excel and I'm having issues as is exporting it as text instead of numeric. Also the qty is empty when there is no value instead of 0. I tried long? and int? but while this works, I prefer to default to 0 if the result is empty.

I can't change the json result. I have tried converting the string to int64 in the get{} but I'm getting errors.

public long id {
        get
        {
            var idCode = Convert.ToInt64(this.id);
            return idCode;

        }
            
            }

Any ideas how I can do this? Keep in mind that I have many other fields like this.

causita
  • 1,607
  • 1
  • 20
  • 32

3 Answers3

0

In such cases you can not use automatic properties and you must use the attribute

public class Error
{
   private long? _id;
   public long id
   {
      get
      {
         return Convert.ToInt64(_id);
      }
      set
      {
         _id = value;
         if (!_id.HasValue)
             _id = 0;
      }
   }
   public string code { get; set; }
   public string message { get; set; }
   public long qty { get; set; }
}
Meysam Asadi
  • 6,438
  • 3
  • 7
  • 17
0

I think you can find the answer to your question here

Convert long number as string in the serialization

with some tweaking

public class Error {

[JsonIgnore]
public long Id{ get; set; }

[JsonIgnore]
public long qty{ get; set; }

[JsonProperty("id")]
public string IdAsString
{
    get { return id.ToString(); }
    set { id = long.Parse(value); }
}

[JsonProperty("qty")]
public string QtyAsString
{
    get { return qty.ToString(); }
    set { qty = long.Parse(value); }
}

}

0

Deserialization.

You need nothing : it will convert with out issue string to int, flaot, decimal etc.
Even if it's a string in the Json : "id":"15006"

public partial class Error
{
    [JsonProperty("id")]
    public long Id { get; set; }
}
var result =JsonConvert.DeserializeObject<RootObject>(input);

Live demo https://dotnetfiddle.net/qliQ8m

Serialization .

You can either use a DTO class with the correct type or custom converter:

internal class ParseStringConverter : JsonConverter
{
    public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);

    public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null) return null;
        var value = serializer.Deserialize<string>(reader);
        long l;
        if (Int64.TryParse(value, out l))
        {
            return l;
        }
        throw new Exception("Cannot unmarshal type long");
    }

    public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
    {
        if (untypedValue == null)
        {
            serializer.Serialize(writer, null);
            return;
        }
        var value = (long)untypedValue;
        serializer.Serialize(writer, value.ToString());
        return;
    }

    public static readonly ParseStringConverter Singleton = new ParseStringConverter();
}

And you decorate your property wi the custom converter: [JsonConverter(typeof(ParseStringConverter))]

public partial class Error
{
    [JsonProperty("id")]
    [JsonConverter(typeof(ParseStringConverter))]
    public long Id { get; set; }

    [JsonProperty("code")]
    public string Code { get; set; }

    [JsonProperty("message")]
    public string Message { get; set; }

    [JsonProperty("qty")]
    public string Qty { get; set; }
}

Default and Null:

You can use JsonSerializer option :

On serialization simply add the parameter like :

string jsonString = 
    JsonConvert.SerializeObject(
        myObject,    
        new JsonSerializerSettings { 
            DefaultValueHandling = DefaultValueHandling.Ignore,
            NullValueHandling = NullValueHandling.Ignore,
        }
    );

Self
  • 349
  • 1
  • 8