簡體   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