简体   繁体   中英

C# Complex Json Deserialization

I was not able to create a working solution with the existing answered questions.

I am successfully using the following c# class

public class country
{
    public string country_id;
    public string country_name;
}

with the following code. The result is a countries list

List<country> countries = new List<country>();  
var streamTask = client.GetStreamAsync("https://xxx");
var serializer = new DataContractJsonSerializer(typeof(List<country>));
countries = serializer.ReadObject(await streamTask) as List<country>;

BUT : now I changed the API and I get a result where I have no clue how to create the class to use the same code.

This is the result of the API call:

{
 "api":{
   "results": 2
   "countries":{
     "1":"Austria"
     "2":"Germany"
    }
  }
}

It is a nested object and "countries" does not even have property names.

How do I deserialize this result?

To start with you will need to change your data contracts:

public class apiResults
{
    public int results;
    public countries countries;
}

public class apiResponse
{
    public apiResults api;
}

[DataContract]
public class countries
{
    [DataMember(Name="1")]
    public string Country1 {get; set;}
}

and then use it as before:

var serializer = new DataContractJsonSerializer(typeof(apiResponse));
var result = serializer.ReadObject(stream) as apiResponse;

Console.WriteLine(result.api.countries.Country1);

The problem here is that you hardcoding the number of available countries. Better way will be to deserialize your new countries class into array.

If you can use NewtonsoftJson - the solution is much easier:

public class apiResults
{
    public int results;
    public Dictionary<int, string> countries { get; set; }
}

public class apiResponse
{
    public apiResults api;
}

and usage:

var result = JsonConvert.DeserializeObject<apiResponse>(responseAsString);
Console.WriteLine(result.api.countries[1]);

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