user7399041
user7399041

Reputation: 137

Deserialize array in JSON into class/object

I'm trying to store JSON data into a class. I could deserialize my otherJSON string into class by: var ser = JsonConvert.DeserializeObject<ClsResult>(myJSON); before I got stuck with array.

    {
      \"Test\": [{
         \"FirstBool\":1, 
         \"aString\":\"hello\"
      }]
    }

This is my class for JSON:

public class Test
{
    [JsonProperty("FirstBool")]
    public bool FirstBool { get; set; }

    [JsonProperty("aString")]
    public string aString { get; set; }
}      

public class ResultObject
{
        [JsonProperty("Test")]
        public List<Test> Test { get; set; }
}

How I deserialize my non-array JSON:

var ser = JsonConvert.DeserializeObject<ResultObject>(myJSON);

What changes do I need to make it work again?

Upvotes: 1

Views: 519

Answers (2)

mrogal.ski
mrogal.ski

Reputation: 5930

Edited answer

Your json string as I've noticed later contains object named Test which is basically an array of objects ( object[] ).

As you can see from the json string :

{ "Test": [{ "FirstBool" : 1, "aString" : "hello" }] }

[ means that json object begins an array type and ] means that json object ended an array type.

{ means that json object begins an object type and } means that json object ended an object type.

Which in your case will require to make kind of a custom deserializer using existing methods from Newtonsoft.Json library.

Example for the Test object could be :

JObject obj = JObject.Parse(jsonString);
// now your obj contains field named "Test" that is of type object[]
// to retrieve informations you have to select "Test" token
JToken testToken = obj.SelectToken("Test");
// your token contains now something like " [{ "FirstBool" : 1, "aString" : "hello" }]"
// which basically is an array
// meaning that you have to iterate through this
foreach(var child in token.Children())
{
    // and convert it to a Test object
    Test test = JsonConvert.DeserializeObject<Test>(child.ToString());
    // test now is fully deserialized object
}

Upvotes: 1

galister
galister

Reputation: 430

Deserialize it as a list:

JsonConvert.DeserializeObject<List<Test>>(json);

...instead of a wrapper object.

Upvotes: 0

Related Questions