In C#, how do I model a JSON object with multiple nested arrays?

别等时光非礼了梦想. 提交于 2019-12-03 14:21:36

I agree the json format is quite ... goofy. Here's how to model your dto:

    public class JsonDto
    {
        public string name { get; set; }
        public Schema[] schema {get; set;}
        public string[][] data { get; set; }
    }
    public class Schema
    {
        public string dataType { get; set; }
        public string colName { get; set; }
        public int idx { get; set; }
    }

I was able to get your string (unaltered) to deserialize with JSON.Net like this:

var jsonDto = JsonConvert.DeserializeObject<JsonDto[]>(json);

Let me know if you're still having trouble.

In Visual Studio 2012 and up and you can go to Edit > Paste Special > Paste JSON as classes. It produces the following code given your example pasted from clipboard.

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public string name { get; set; }
    public Schema[] schema { get; set; }
    public string[][] data { get; set; }
}

public class Schema
{
    public string dataType { get; set; }
    public string colName { get; set; }
    public int idx { get; set; }
}

string json = File.ReadAllText("json.txt");
Rootobject root = new Rootobject();
root.Property1 = JsonConvert.DeserializeObject<Class1[]>(json);

Do you have any control over the structure of the JSON being returned? It's kind of wacky. For some reason the field names and the data is separated out. If the format was a little more sensible like:

[
    {
        "First": "bill",
        "Second": "test",
        "Name": "joe"
    },

    {
        "First": "bill2",
        "Second": "test2",
        "Name": "joe2"
    },
]

Then you would have a shot at serializing it to your Ticket class. However, without reworking the JSON structure, which I don't recommend you do, the C# class that you are serializing to will have to match the JSON structure.

I suppose you could come up with an intermediary class to hold the JSON data as it comes to you. Then you could loop over those objets and create instances of the Ticket class out of them. At least that way you end up with a data structure you can work with.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!