简体   繁体   English

C#复杂的Json反序列化

[英]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 我成功使用以下c#类

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. 但是 :现在我更改了API,但得到的结果是我不知道如何创建使用相同代码的类。

This is the result of the API call: 这是API调用的结果:

{
 "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: 如果您可以使用NewtonsoftJson-解决方案将更加容易:

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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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