2

I have this json file:

{
  "timestamp": 1557323147422,
  "change_id": 11687520784,
  "data": [
      [ "new", 5775.0, 16530.0 ],
      [ "new", 5774.5, 360.0 ]
  ]
}

I need to set up a class to deserialize it, but the data array is causing me a problem.

I tried to map data to:

List<(string, double, double)>

but that doesn't work. List works, but then it's just pushing the problem one step away.

I can map it to

List<dynamic>

and then I get a list of JArray that I need to parse individually.

What I need is to be able to map it to some class that has a string and 2 doubles.

Thomas
  • 10,933
  • 14
  • 65
  • 136
  • maybe `tuple` ? – demo May 08 '19 at 14:04
  • @demo well he tried a tuple with `List<(string, double, double)>` – Rand Random May 08 '19 at 14:07
  • yes, that doesn't work: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Tuple`3[System.String,System.Double,System.Double]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. – Thomas May 08 '19 at 14:07
  • I can do a List> but then I have to parse the doubles after that – Thomas May 08 '19 at 14:09
  • JYou need to write your own ContractResolver for this transformation. And you cannot use Value Tuples instead of classic System.Tuple class in your code - JSON.NET cannot map it by name yet (see this: https://github.com/JamesNK/Newtonsoft.Json/issues/1230 ) – Dmitriy May 08 '19 at 14:20
  • Here many examples of contracts which allow you to solve your task in a easy way: https://stackoverflow.com/questions/41088492/json-net-contractresolver-vs-jsonconverter – Dmitriy May 08 '19 at 14:42
  • @Dmitriy Awesome, thanks! – Thomas May 08 '19 at 14:48
  • 1
    Nope. In the future if you will use .NET Core >= 3.0, pls, read about new MS .Net json serializer which will replace JSON.NET. – Dmitriy May 08 '19 at 14:50
  • That is fundamentally a list of lists of values. You can use Json.net and do the serialization more by hand, but I doubt you will be able to get it to just deserialize a list into an object directly. – Lasse V. Karlsen May 08 '19 at 16:58

2 Answers2

0

You can use http://json2csharp.com/

I generated this code:

public class RootObject
{
    public long timestamp { get; set; }
    public long change_id { get; set; }
    public List<List<object>> data { get; set; }
}
emert117
  • 1,268
  • 2
  • 20
  • 38
  • yes, that's what I wrote about in the question, it just shifts the problem to parsing the object. – Thomas May 08 '19 at 14:06
0

Your array is still an array of object in JSON, it is neither a tuple nor a type.

So List<List<object>> (or IEnumerable<IEnumerable<object>>) seems to be the only option.

the_joric
  • 11,986
  • 6
  • 36
  • 57