简体   繁体   中英

Deserialize JSON from multiple objects to list of objects

Unable to create mapping object / response model for the received JSON response from the service.

Tried of creating custom JsonConverter but could not find any appropriate method which can help to resolve the Deserializing issue

The following is the JSON response which i am getting from the Service.

{
    "$base": "Collection",
    "nodeType": "PROTOCOL",
    "Smart Building 0": {
        "$base": "Collection",
        "nodeType": "NETWORK",
        "truncated": "true"
    },
    "Smart Building 1": {
        "$base": "Collection",
        "nodeType": "NETWORK",
        "truncated": "true"
    },
    "Smart Building 2": {
        "$base": "Collection",
        "nodeType": "NETWORK",
        "truncated": "true"
    }
}

Example 1:- Same service can return below JSON format

{
    "$base": "Collection",
    "nodeType": "PROTOCOL",
    "Smart Building 0": {
        "$base": "Collection",
        "nodeType": "NETWORK",
        "truncated": "true"
    },
    "Smart Building 1": {
        "$base": "Collection",
        "nodeType": "NETWORK",
        "truncated": "true"
    }
}

Create c# root object class so that it can easily used to Deserializing using JsonConvert

Try this one:

public class Root : Dictionary<string, Building>
{   
    [JsonProperty("$base")]
    public string Base { get; set; }

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

public class Building
{
    [JsonProperty("$base")]
    public string Base { get; set; }

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

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

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