André
André

Reputation: 318

How to parse JSON array of string arrays

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.

Upvotes: 5

Views: 10857

Answers (3)

Ted James
Ted James

Reputation: 121

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

Upvotes: 0

yohannist
yohannist

Reputation: 4204

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

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502236

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
    }
}

Upvotes: 14

Related Questions