简体   繁体   中英

Deserialize json array to c# list object

I am trying to parse a JSON response from a service to c# observation collection list object. The list object later can be used to showcase on the XAML page.

Here is the response from the service:

[
  {
    "orderId": 1,
    "employeeId": "6364",
    "orderTime": 1517583600000,
    "orderCost": 90,
    "comments": null,
    "orderStatus": {
      "orderStatusId": 1,
      "orderStatusName": "Order Placed"
    },
    "orderedItems": [
      {
        "orderItemId": 1,
        "orderQuantity": 1,
        "orderItemCost": 50
      },
      {
        "orderItemId": 2,
        "orderQuantity": 1,
        "orderItemCost": 40
      }
    ]
  },
  {
    "orderId": 2,
    "employeeId": "6364",
    "orderTime": 1517670000000,
    "orderCost": 50,
    "comments": null,
    "orderStatus": {
      "orderStatusId": 3,
      "orderStatusName": "Order Delivered"
    },
    "orderedItems": [
      {
        "orderItemId": 3,
        "orderQuantity": 1,
        "orderItemCost": 50
      }
    ]
  }
]

The following is the model class :

namespace ServiceNew
{

    public class OrderStatus
    {
        public int orderStatusId { get; set; }
        public string orderStatusName { get; set; }
    }

    public class OrderedItem
    {
        [JsonProperty("orderItemId")]
        public int orderItemId { get; set; }

        [JsonProperty("orderQuantity")]
        public int orderQuantity { get; set; }

        [JsonProperty("orderItemCost")]
        public int orderItemCost { get; set; }
    }

    public class Order
    {
        [JsonProperty("orderId")]
        public int orderId { get; set; }

        [JsonProperty("employeeId")]
        public string employeeId { get; set; }

        [JsonProperty("orderTime")]
        public object orderTime { get; set; }
        [JsonProperty("orderCost")]
        public int orderCost { get; set; }

        [JsonProperty("comments")]
        public object comments { get; set; }

        [JsonProperty("orderStatus")]
        public OrderStatus orderStatus { get; set; }

        [JsonProperty("orderedItems")]
        public List<OrderedItem> orderedItems { get; set; }
    }


}

The service is like this:

public  class OrderService
    {
        public OrderService()
        {
            GetJson();
        }
        public async void GetJson()
        {
            if (NetworkCheck.IsInternet())
            {
                var client = new System.Net.Http.HttpClient();
                var response = await client.GetAsync("here is thre URL");
                string orderJson = await response.Content.ReadAsStringAsync(); //Getting response  

                Order ObjOrderList = new Order();
                if (orderJson != " ")
                {

                    Console.WriteLine("response is"+orderJson);

                   //exception occurs here all the time , and I need it to be a list
                    ObjOrderList = JsonConvert.DeserializeObject<Order>(orderJson);
                }

                Console.WriteLine("obj order list is"+ObjOrderList);
            }
        }
    }

After trying with some changes to the deserialization the JSON array to c#, I was not able to succeed. Now there is an exception saying

Newtonsoft.Json.JsonSerializationException: <Timeout exceeded getting exception details>

And I am stuck at this for a long time, searched over StackOverflow and googled it but no fruitful solution for this.

I need to store the JSON data into ac# object and reproduce the same object in the XAML page as a list.

Thanks in advance!

I am sure that exception is not related to you JSON string but try to remove bin and obj from solution folder and then clean and rebuild solution.

but after resolving that you will get the below exception

Cannot deserialize the current JSON array (eg [1,2,3]) into type 'namespace.Order' because the type requires a JSON object (eg {"name":"value"}) to deserialize correctly.....

Because your JSON string is List of Order so the deserialize would be change to :

List<Order> ObjOrderList = JsonConvert.DeserializeObject<List<Order>>(orderJson);

or in the other side you can also use JavaScriptSerializer like:

Order[] orderList = new JavaScriptSerializer().Deserialize<Order[]>(orderJson);

Your JSON starts with a [ and ends with a ] . This means that your JSON represents an array of objects. These objects are:

First object

{
    "orderId": 1,
    "employeeId": "6364",
    "orderTime": 1517583600000,
    "orderCost": 90,
    ...
}

Second object

{
    "orderId": 2,
    "employeeId": "6364",
    "orderTime": 1517670000000,
    "orderCost": 50,
    ...
}

In your subconscious you knew it, in fact the name of your deserialized variable is ObjOrderList (highlight List ).

So, just deserialize to an array/list of Order .

Example with list

var ObjOrderList = new List<Order>();
if (orderJson != " ")
{
    //exception occurs here all the time , and I need it to be a list
    ObjOrderList = JsonConvert.DeserializeObject<List<Order>>(orderJson);
}

Example with array

var ObjOrderList = new Order[] { };
if (orderJson != " ")
{
    //exception occurs here all the time , and I need it to be a list
    ObjOrderList = JsonConvert.DeserializeObject<Order[]>(orderJson);
}

You are deserializing a List of Orders so you should deserialize like this:

...
List<Order> ObjOrderList;
...
ObjOrderList = JsonConvert.DeserializeObject<List<Order>>(orderJson);
...

Try this autogenerated code:

// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using yourNameSpace;
//
//    var orderResponse = OrderResponse.FromJson(jsonString);

namespace yourNameSpace
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

public partial class OrderResponse
{
    [JsonProperty("orderId")]
    public long OrderId { get; set; }

    [JsonProperty("employeeId")]
    public string EmployeeId { get; set; }

    [JsonProperty("orderTime")]
    public long OrderTime { get; set; }

    [JsonProperty("orderCost")]
    public long OrderCost { get; set; }

    [JsonProperty("comments")]
    public object Comments { get; set; }

    [JsonProperty("orderStatus")]
    public OrderStatus OrderStatus { get; set; }

    [JsonProperty("orderedItems")]
    public List<OrderedItem> OrderedItems { get; set; }
}

public partial class OrderStatus
{
    [JsonProperty("orderStatusId")]
    public long OrderStatusId { get; set; }

    [JsonProperty("orderStatusName")]
    public string OrderStatusName { get; set; }
}

public partial class OrderedItem
{
    [JsonProperty("orderItemId")]
    public long OrderItemId { get; set; }

    [JsonProperty("orderQuantity")]
    public long OrderQuantity { get; set; }

    [JsonProperty("orderItemCost")]
    public long OrderItemCost { get; set; }
}

public partial class OrderResponse
{
    public static List<OrderResponse> FromJson(string json) => JsonConvert.DeserializeObject<List<OrderResponse>>(json);
}

code was generated using QuickType.io I discarded the converter and some other extra classes. You can change the Long type to int if you want.

To use it just call

var orderResponse = OrderResponse.FromJson(jsonString);

pass the response instead of jsonString

In this Code you can DeserializeObject json file:

 using (StreamReader r = new StreamReader("D:/Source/ParsijooWeatherApi/ParsijooWeatherApi/cities2.json"))
        {
            string json = r.ReadToEnd();
            List<jsonVariables> items = JsonConvert.DeserializeObject<List<jsonVariables>>(json);

            dynamic array = JsonConvert.DeserializeObject(json);
            foreach (var item in array)
            {
                Console.WriteLine("{0} {1}", item.latitude, item.longitude);
            }
        }

jsonVariables class is:

public class jsonVariables
{
    [JsonProperty("latitude")]
    public string latitude { get; set; }

    [JsonProperty("longitude")]
    public string longitude { get; set; }

    [JsonProperty("state")]
    public string state { get; set; }
}

In this code you access to root directory project:

 string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

then:

StreamReader r = new StreamReader(_filePath + "/cities2.json"))

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