开发者

Trouble Deserializing JSON into Object

开发者 https://www.devze.com 2023-04-07 22:37 出处:网络
Stack Overflow: I am using JSON.NET and have done so successfully before, however I am now running into a nasty bit of JSON that I cannot seem to deserialize. Clearly the problem lays in how the clas

Stack Overflow:

I am using JSON.NET and have done so successfully before, however I am now running into a nasty bit of JSON that I cannot seem to deserialize. Clearly the problem lays in how the class is constructed, and so I kindly ask for someone to help me plan a class that JSON.NET can successfully deserialize into.

Here is the structure of the JSON string:

[
    {
        "name":"",
        "cost":"",
        "cmc":"",
        "loyalty":"",
        "supertype":"",
        "type":"",
        "subtype":"",
        "power":"",
        "toughness":"",
        "hand":"",
    开发者_StackOverflow    "life":"",
        "rule":"",
        "multi":"",
        "set":
        [   // Note: there could be an infinite number of sets
            {
                "setcode":"",
                "rarity":"",
                "number":"",
                "artist":"",
                "flavor":""
            },
            {   "setcode":"",
                "rarity":"",
                "number":"",
                "artist":"",
                "flavor":""
            },
        ]
    }
]

Thank you very much, Stack Overflow


You'll want to have a class with properties for all those names. When it comes to the array, it's really an array of objects so you need to create another class with same named properties. Something like:

public class MainObject
{
    public string name { get;set; }
    // rest of the names as properties
    public List<SetObject> @set { get;set; }

}

public class SetObject
{
    public string setcode { get;set; }
    // rest of your sets names as properties
}

Also, from your JSON it looks like it's an array already so you'll want to deserialize it as an array:

var objects = JsonConvert.DeserializeObject<MainObject[]>(/* your json here */);

That will give you an array of your deserialized MainObject just like your JSON is an array.

0

精彩评论

暂无评论...
验证码 换一张
取 消