简体   繁体   中英

How can I deserialize a json string in to a model?

Hello Everyone ,

A json model like the one below makes me return via an api.

 {
  "data": [
    {
      "countryStats": {
        "order": 2,
        "confirmedCount": 15679,
        "deathCount": 277,
        "recovryCount": 333,
        "name": "Türkiye"
      },
      "cityStats": [

      ]
    },
    {
      "countryStats": {
        "order": 1,
        "confirmedCount": 216722,
        "deathCount": 5138,
        "recovryCount": 8672,
        "name": "Amerika Birleşik Devletleri"
      },
      "cityStats": [
        {
          "order": 1,
          "confirmedCount": 84070,
          "deathCount": 1941,
          "recovryCount": 0,
          "name": "New York"
        },..

I am pulling this json data with the code below.

static string GET(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            try
            {
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
                    return reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                    // log errorText
                }
                throw;
            }
        }

Here comes a string expression for me. I want to assign this string expression to my model, how do I do that.

My model

public class CountryStats
    {
        public int Order  { get; set; }
        public int ConfirmedCount { get; set; }
        public int DeathCount { get; set; }
        public int RecovryCount { get; set; }
        public string Name { get; set; }
        public List<CountryStats> CityStats { get; set; }
    }

I'm trying to translate it like this

var result = JsonConvert.DeserializeObject<List<CountryStats>>(res);

But I get an error

在此处输入图片说明

You must change the model to this

public class BaseClass
{
    public List<CountryStats> Data { get; set; }
}
public class CountryStats
{
    public int Order  { get; set; }
    public int ConfirmedCount { get; set; }
    public int DeathCount { get; set; }
    public int RecovryCount { get; set; }
    public string Name { get; set; }
    public List<CountryStats> CityStats { get; set; }
}

then deserialize response to BaseClass

var result = JsonConvert.DeserializeObject<BaseClass>(res);

Update

try this to deserialize Turkish word

res = res.Replace("\"","'");
var result = JsonConvert.DeserializeObject<BaseClass>(res);

or

var result = HttpUtility.JavaScriptStringEncode(JsonConvert.DeserializeObject<BaseClass>(res));

The problem is your model. It should look like below.

public class CountryStatsCollection
{
    public List<ContryStats> Data { get; set }
}

public class CountryStats
    {
        public int Order  { get; set; }
        public int ConfirmedCount { get; set; }
        public int DeathCount { get; set; }
        public int RecovryCount { get; set; }
        public string Name { get; set; }
        public List<CountryStats> CityStats { get; set; }
    }

In addtion to other answers, if you are not sure that some fields may be null or not, this would help:

public partial class Welcome
{
    [JsonProperty("data", NullValueHandling = NullValueHandling.Ignore)]
    public List<Datum> Data { get; set; }
}

public partial class Datum
{
    [JsonProperty("countryStats", NullValueHandling = NullValueHandling.Ignore)]
    public CountryStats CountryStats { get; set; }

    [JsonProperty("cityStats", NullValueHandling = NullValueHandling.Ignore)]
    public List<object> CityStats { get; set; }
}

public partial class CountryStats
{
    [JsonProperty("order", NullValueHandling = NullValueHandling.Ignore)]
    public long? Order { get; set; }

    [JsonProperty("confirmedCount", NullValueHandling = NullValueHandling.Ignore)]
    public long? ConfirmedCount { get; set; }

    [JsonProperty("deathCount", NullValueHandling = NullValueHandling.Ignore)]
    public long? DeathCount { get; set; }

    [JsonProperty("recovryCount", NullValueHandling = NullValueHandling.Ignore)]
    public long? RecovryCount { get; set; }

    [JsonProperty("name", NullValueHandling = NullValueHandling.Ignore)]
    public string Name { get; set; }
}

Then you can deserialize it:

var result = JsonConvert.DeserializeObject<Welcome>(res);

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