简体   繁体   English

如何在C#中获取JSON对象的属性名称

[英]How to get property name of JSON Object in C#

Here's a sample JSON data: 这是一个示例JSON数据:

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

In C# function, I do this to convert this data into my C# object: 在C#函数中,我这样做是将数据转换为C#对象:

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 ? 现在,如何从jsonObj获得此"data_header"值?

Thanks for any help. 谢谢你的帮助。

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. Shanid,您提到您尝试过@JayakrishnanGounder解决方案,但遇到错误,可能是您的模型可能未设计为处理JSON数据结构。

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. 因此,现在您应该可以使用JSON.net反序列化的@JayakrishnanGounder方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM