Dante4
Dante4

Reputation: 13

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.

Upvotes: 0

Views: 88

Answers (2)

L.B
L.B

Reputation: 116118

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());

Upvotes: 2

Rick Wolff
Rick Wolff

Reputation: 777

As @Alex has said in the comments:

As far as reading it goes, anything contained inside [ ] is considered an array. So the "items" field is an array containing arrays

If you don't want to have this array of arrays, you can create a new class to encapsulate the inner array. For instance:

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

And your classes in C# would be:

public class Parent
{
  public List<Child> items;
  public int updated;
  public string[] columns;

  public Parent()
  {
    items = new List<Child>();
  }
}

public class Child
{
  public string[] numbers;
}

Something like that.

Upvotes: 0

Related Questions