简体   繁体   中英

Deserialize JSON to c# dictionary // Problem with structure

I want to deserialize JSON that looks like this:

{
    "rooms":{
        "room1":{
            "id":"bPhJoQTTE",
            "roomName":"room1"
        },
         "room2":{
            "id":"bPh1oqLTE",
            "roomName":"room2"
        }
    }
}

I'm using the following class definitions for deserialization:

public class Room
{
    public string id;
    public string roomName;
}

public class Rooms
{
    public Dictionary<string, Room> room;
}

public class Root
{
    public Rooms rooms;
}

And here's the code I'm using to perform the deserialization:

Root deserializationObj = JsonConvert.DeserializeObject<Root>(json);

It's not working - what am I doing wrong?

You shouldn't need the Rooms class at all. Try updating Root to look like this:

public class Root
{
    public Dictionary<string, Room> rooms;
}

Also, your Room class has a username property that isn't in your example JSON, and it's missing the roomName property from your example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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