Search code examples
c#json.netjson-deserialization

C# JSON.net Deserialization


Yesterday was first day when i met JSON and most of example that i find was where JSON have format like

{ "key1": "value1", "key2": "value2", ... }

but i have json string:

{"items":[[24,68,216,34006,32224],[68,177,277,140,2130], |...skip big amount of data....| ,[79606,8500392,0,0,14]],"updated":1475686082000,"columns":["id","buy","sell","supply","demand"]}

I trying to figure out how to read this and get specific amount of data. As example i need to get number in column "buy" and "sell" of specific IDs.


Solution

  • According to your json your model should be

    public class YourRootObject
    {
        public List<List<int>> items { get; set; }
        public long updated { get; set; }
        public List<string> columns { get; set; }
    }
    

    and now you can deserialize as

    var obj = JsonConvert.DeserializeObject<YourRootObject>(json);
    

    But, Instead of dealing with "updated" value later, I would change the model as below and write a json converter.

    public class YourRootObject
    {
        public List<List<int>> items { get; set; }
        public DateTime updated { get; set; }
        public List<string> columns { get; set; }
    }
    
    public class EpochToDatetimeConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var l = (long)reader.Value;
            return new DateTime(1970, 1, 1).AddMilliseconds(l).ToLocalTime();
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

    Now you can deserialize as

    var obj = JsonConvert.DeserializeObject<YourRootObject>(json, 
                                               new EpochToDatetimeConverter());