5

Lets say I get the following json data from a web service which I can't change.

[
    [
        "Header1",
        "Header2",
        "Header3",
        "Header4"
    ],
    [
        "FirstValue1",
        "FirstValue2",
        "FirstValue3",
        "FirstValue4"
    ],
    [
        "SecondValue1",
        "SecondValue2",
        "SecondValue3",
        "SecondValue4"
    ]
]

jsonlint.com tells me that it is valid json and from what I know I would agree.

But somehow I'm wondering is there any "easy" way to deserialize this to a class. Each of the values in the second and third array belongs to the corresponding header in the first array.

I know how to use Json.NET but can't get my head around on how to use it with this data structure.

1
  • You deserialize the data and then reorganize however you want. Commented Jun 23, 2015 at 9:06

3 Answers 3

14

Simple - you can use JsonConvert.DeserializeObject to deserialize it to a string[][]:

using System;
using System.IO;
using Newtonsoft.Json;

class Test
{
    static void Main()
    {
        var json = File.ReadAllText("test.json");
        string[][] array = JsonConvert.DeserializeObject<string[][]>(json);
        Console.WriteLine(array[1][3]); // FirstValue4
    }
}
Sign up to request clarification or add additional context in comments.

Comments

4

The easiest way is to use the string class and deserialzie it using Json.NET.

string[][] values = JsonConvert.DeserializeObject<string[][]>(json);

Comments

0

A better option could be to use

using Newtonsoft.Json.Linq

string json = @"{
  CPU: 'Intel',
  Drives: [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}";

JObject o = JObject.Parse(json); 

string CPU = o.CPU;
int NumDrives = o.Drives.Count;

Source: http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_Parse.htm

3 Comments

That's not going to work. JObject doesn't know about CPU or Drives. You'd need to use dynamic for that. And your JSON is completely different from the question asked.
It was an example... and if you tired the code... you would see what it does work.
It doesn't work - as expected I get 'JObject' does not contain a definition for 'CPU' and no accessible extension method 'CPU' accepting a first argument of type 'JObject' could be found (are you missing a using directive or an assembly reference?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.