How to Deserialize JSON data? C#

前端 未结 5 1547
感情败类
感情败类 2020-12-22 10:22

Im getting a Json Data from an API and i have been trying to deserialize.

Json data:

{
   \"items\": [
      {
         \"id\": \"1\",
         \"nam         


        
相关标签:
5条回答
  • 2020-12-22 10:39

    Try Below Code

    JsonConvert.DeserializeObject<Users>(content);
    
    0 讨论(0)
  • 2020-12-22 10:40

    The following is a JSON-object; in your case a User

    { ... }
    

    The following is a JSON-array; in your case an array of User

    [ { ... }, { ... } ]
    

    Thus if you want to deserialize the JSON you got into an array of Users this is not possible because you have no array in JSON.

    Therefore the right code to deserialize is:

    JsonConvert.DeserializeObject<Users>(content);
    

    Furthermore your mapping is erroneous because in JSON there is a property AddressList1 and in the class it is called addressList1

    0 讨论(0)
  • 2020-12-22 10:43

    Your Json string is good formatted and the entities are according to Json2Csharp good too.

    but your problem is with the instruction JsonConvert.DeserializeObject<List<Users>>(content);

    all that json that you have is only ONE User, and you are trying to get a list of them, there is the issue,

    you can try instead with:

    JsonConvert.DeserializeObject<Users>(content);
    
    0 讨论(0)
  • 2020-12-22 10:54

    Your entities(models) look just fine. If you are using, or were to use ASP.NET Web API 2, and your client is using the http verb post for example, this setup would work as Web API takes care of the object deserialization:

        public HttpStatusCode Post(Item item)
        {
           Debug.Write(item.toString());
           return HttpStatusCode.OK;
        }
    

    If you insist in deserializing manually then use the JavaScriptSerializer library which allows you to do things like:

    Item item = new JavaScriptSerializer().Deserialize<Item>(content);
    

    Notice that .Deserialize<T>() takes a generic which in your case it Item.

    Hope that helps.

    0 讨论(0)
  • 2020-12-22 10:55

    Given your JSON, you would need a POCO object that contains a items member and a paging member.

    JsonConvert.DeserializeObject<Users>(content);
    

    should work.

    0 讨论(0)
提交回复
热议问题