Deserializing JSON with unknown fields

2019-03-01 06:49发布

问题:

I'm trying to deserialize some JSON I receive from an external source (no way to change it) and I'm having some problems with it. I'm using JSON.net to deserialize, and this is an example of what I receive:

{
    "uploaded":
    {
        "name":"Uploaded by me",
        "size":3768,
        "last_change_time":1310470698
    },
    "tagged":
    {
        "name":"Photos I'm tagged in",
        "size":6937,
        "last_change_time":1311730303
    },
    "4019677_60607060":
    {
        "name":"Asad",
        "size":63,
        "last_change_time":1271315304
    },
    "4611824_60607060":
    {
        "name":"ASDF",
        "size":64,
        "last_change_time":1262645480
    }
}

This way, I create an object Albums and an object Album

[DataContract]
public class Albums
{
    [DataMember]
    public Album uploaded  { get; set; }
    [DataMember]
    public Album tagged { get; set; }
}

[DataContract]
public class Album
{
    [DataMember]
    public string name { get; set; }
    [DataMember]
    public int size { get; set; }
    [DataMember]
    public int last_change_time { get; set; }
}

And as you can see, with the Albums object I've got a problem, because there's no way I know what would be the album's id, and therefore, no way I create a field in Albums with that id. Uploaded and tagged fields atre I think there should be an option in JSON.net to achieve this but I can't find it...

Thank you all

回答1:

the JSON recieved seems to be a dictionnary..

did you try to deseserialize as a Dictionnary<string,Album> ?