解析嵌套的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字符串有多个房间,但是如果我添加列表,它会引发异常。上面的这条线经历了,但是我的房间和溪流都为空。

我还试图将房间课程构建为

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

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

编辑:

我更改了JSON看起来像这样,现在正在解析。

[
{
    "room":"room1",
    "first": "id1",
    "second": "id2",
    "third": "id3"
},
{
    "room":"room1",
    "first": "id1",
    "second": "id2",
    "third": "id3"
}

]

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

您的类是错误的,对于此对象

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; }
}

然后

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

编辑:OP表示将有很多房间

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

相关内容

  • 没有找到相关文章

最新更新