1

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?

1
  • Are you sure FirstBool should be a bool? It's an int in the JSON. Commented Jan 25, 2017 at 10:43

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

By you recommendation, should I change public List<Test> Test { get; set; } to public Test Test { get; set; } as well?
@user7399041 Sorry my bad. I haven't read your sample json string. Now this should work as intended.
Thanks a lot for the well explained edited answer :) Works really well.
0

Deserialize it as a list:

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

...instead of a wrapper object.

2 Comments

Should I change public List<Test> Test { get; set; } to public Test Test { get; set; } as well?
You don't need the ResultObject at all! It's just a wrapper right now, let JsonConvert handle it for you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.