Shanid
Shanid

Reputation: 587

How to get property name of JSON Object in C#

Here's a sample JSON data:

{"data_header":"[
    {   
        "id":"1",
        "name":"aa"
    },
    {   
        "id":"2",
        "name":"bb"
    }
]"}

In C# function, I do this to convert this data into my C# object:

JObject jsonObj = JObject.Parse(jsonData);
JArray arr = (JArray)jsonObj["data_header"];
MyModel model = arr.ToObject<MyModel>();

Works fine. Now, how do I get this "data_header" value from jsonObj ?

Thanks for any help.

Upvotes: 1

Views: 7181

Answers (1)

Jay
Jay

Reputation: 21

Shanid,you mentioned you tried @JayakrishnanGounder solution and you got an error, is it possible your model may not be designed to handle the JSON data structure.

public class NameModel
{
   [JsonProperty("id")]
   public int id {get;set;}

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

public class ContainerModel
{
   [JsonProperty("data_header")]
   public List<NameModel> data_headeer
}

So now you should be able @JayakrishnanGounder method of deserialize using JSON.net.

var model = JsonConvert.DeserializeObject<ContainerModel>(json);

Upvotes: 2

Related Questions