Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse JSON array of string arrays

Tags:

json

c#

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.

like image 678
André Avatar asked Dec 04 '22 03:12

André


2 Answers

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
    }
}
like image 73
Jon Skeet Avatar answered Dec 28 '22 03:12

Jon Skeet


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

string[][] values = JsonConvert.DeserializeObject<string[][]>(json);
like image 41
yohannist Avatar answered Dec 28 '22 03:12

yohannist