简体   繁体   中英

Deserializing JSON from API call Dynamically

An API call that I use returns a JSON similar to below

{
    "d": {
        "results": [
            {
                "Id": "Test01",
                "Version": ""

            }
        ],
        "count": 0
    }
}

Is there anyway I can Deserialize this Dynamically or Should I create POCO classes to do so ?

For your question, I am using the Newtonsoft JSON library which is a popular high-performance JSON framework for .NET.

You can go both ways here to de-serialize your JSON string:

1) Using POCO classes for your JSON string:

public class Result
{
    public string Id { get; set; }
    public string Version { get; set; }
}

public class D
{
    public List<Result> results { get; set; }
    public int count { get; set; }
}

public class RootObject
{
    public D d { get; set; }
}

To de-serialize:

var Sresponse = JsonConvert.DeserializeObject<RootObject>(json);

OR

2) You can use dynamic if you do not want to use the POCO classes:

var dynamicresponse = JsonConvert.DeserializeObject<dynamic>(json);

Output:

Id: Test01
Version: 
Count: 0

A working example illustrating both the cases can be found here :

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