繁体   English   中英

反序列化Json对象C#

[英]Deserialize the Json Object C#

我想反序列化下面的Json对象,

var jsonObject = {
    "name": "sections",
    "record": [
        { 
            "id": 1,
            "name": "sections",
            "tables": 
            {
                "sections": 
                {
                    "id": "1",
                    "type": "2"
                }
            }
        }
    ]
}

在C#中

var result = JsonConvert.DeserializeObject<Response>(jsonObject);

添加了以下反序列化类

public class Response
        {
            [JsonProperty("name")]
            public string Name;

            [JsonProperty("record")]
            public List<Records> Record;
        }

        public class Records
        {
            [JsonProperty("id")]
            public int Id;

            [JsonProperty("name")]
            public string Name;

            [JsonProperty("tables")]
            public List<Table> Tables;

        }

        public class Table
        {
            [JsonProperty("sections")]
            public List<Sections> Sections;
        }

        public class Sections
        {
            [JsonProperty("id")]
            public string id;

            [JsonProperty("type")]
            public string Type;

        }

我想从json中获取“类型”,但未正确反序列化。 任何人都可以建议如何从Json对象获取Type。

从问题来看,班级不匹配。

public class Response
        {
            public string Name;
            public List<Records> Record;
        }

        public class Records
        {
            public int Id;
            public string Name;
            public List<Table> Tables;
        }

        public class Table
        {
            public List<Sections> Sections;
        }

        public class Sections
        {
            public string id;
            public string Type;

        }

节没有[],表也没有,因此它们不是列表。

我也将您的反序列化代码更改为此

var result = JsonConvert.DeserializeObject<Response>(jsonObject, new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

因此,您不必仅为骆驼式JSON注释每个类属性。

由于属性type格式不正确,因此无法序列化对象。
代替

type ": "
                    2 "

您必须将type设置如下

"type":"2"

暂无
暂无

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

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