解析嵌套的 json 在对象中返回 null

我有以下json。


{

    "room1": {

        "first": "id1",

        "second": "id2",

        "third": "id3"

    },

    "room2": {

        "first": "id1",

        "second": "id2",

        "third": "id3"

    }

}

我正在尝试对这两个类进行反序列化。


public class Streams

    {

        [JsonProperty("first")]

        public string first { get; set; }


        [JsonProperty("second")]

        public string second { get; set; }


        [JsonProperty("third")]

        public string third { get; set; }

    }


    public class Room

    {

            public string room { get; set; }

            public Streams streams { get; set; }

    }

我当前的代码很简单:


Rooms r = JsonConvert.DeserializeObject<Rooms>(jsonstring);

我知道我的 json 字符串有多个房间,但是如果我添加 List 它会引发异常。上面的这条线通过了,但是我得到了房间和流的空值。


我还尝试将 Rooms 类构建为


Dictionary<string, Streams> d { get; set; }

这没有引发异常,但仍然返回 null。


编辑:


我把 json 改成这样,现在解析得很好。


[

{

    "room":"room1",

    "first": "id1",

    "second": "id2",

    "third": "id3"

},

{

    "room":"room1",

    "first": "id1",

    "second": "id2",

    "third": "id3"

}

]


ABOUTYOU
浏览 280回答 2
2回答

守着星空守着你

你的类对于这个对象是错误的public class JsonClass{&nbsp; &nbsp; public RoomClass room1 {get; set;}&nbsp; &nbsp; public RoomClass room2 {get; set;}}public class RoomClass{&nbsp; &nbsp; [JsonProperty("first")]&nbsp; &nbsp; public string first { get; set; }&nbsp; &nbsp; [JsonProperty("second")]&nbsp; &nbsp; public string second { get; set; }&nbsp; &nbsp; [JsonProperty("third")]&nbsp; &nbsp; public string third { get; set; }}然后var result = JsonConvert.DeserializeObject<JsonClass>(jsonstring);编辑:OP表示会有很多房间var result = JsonConvert.DeserializeObject<IDictionary<string, RoomClass>>(jsonstring);

暮色呼如

public class Rooms{&nbsp; &nbsp; &nbsp; &nbsp; public Streams room1{ get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public Streams room2{ get; set; }}Rooms r = JsonConvert.DeserializeObject<Rooms>(jsonstring);
打开App,查看更多内容
随时随地看视频慕课网APP