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

时间:2018-12-19 11:03:03

标签: c# json json.net

我有以下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"
}

]

2 个答案:

答案 0 :(得分:0)

public class Rooms
{
        public Streams room1{ get; set; }
        public Streams room2{ get; set; }
}
Rooms r = JsonConvert.DeserializeObject<Rooms>(jsonstring);

答案 1 :(得分:0)

your classes is wrong for this object

public class JsonClass
{
    public RoomClass room1 {get; set;}
    public RoomClass room2 {get; set;}
}

public class RoomClass
{
    [JsonProperty("first")]
    public string first { get; set; }

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

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

then

var result = JsonConvert.DeserializeObject<JsonClass>(jsonstring);

Edit: OP stated that there will be many rooms

var result = JsonConvert.DeserializeObject<IDictionary<string, RoomClass>>(jsonstring);