13

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 a c# object and reproduce the same object in the XAML page as a list.

Thanks in advance!

3
  • See if the ex.InnerException has any details Commented May 15, 2018 at 5:43
  • The innerException has nothing Commented May 15, 2018 at 5:55
  • async void is a code smell when not for event handler, long term operation in constructor is a code smell too Commented May 15, 2018 at 6:02

5 Answers 5

20

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 (e.g. [1,2,3]) into type 'namespace.Order' because the type requires a JSON object (e.g. {"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);
Sign up to request clarification or add additional context in comments.

1 Comment

Just a little Note: you can also use JsonConvert as JsonConvert.DeserializeObject<Order[]>(json);
4

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

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

3 Comments

I have changed the code but still the same exception exists.
Is your service code the original or a manually stripped down sample?
Actually this worked for me ...to day I have changed the code and it worked perfectly... thank you so much
2

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

4 Comments

thanks for the reply, I have changed the code accordingly, but there is Newtonsoft.Json.JsonReaderException: <Timeout exceeded getting exception details> but I like the word SUBCONSCIOUS.
I executed the code I posted with no errors. Try to put your JSON in a variable and then execute your code. I put the JSON in a file and then read it using: string orderJson = File.ReadAllText(@"C:\file.txt");. Then execute your code. This ensure that your problem is not related to the input.
But the json i am using is not from a variable, it is coming from a service, so I cant get the json from a text file
Yes, it's just for debugging. Put your example JSON (the one you posted in the question) in a file and save it. Then use File.ReadAllText to get the file content. In this way you can understand if the problem is from the request's response or from the JSON itself (which shouldn't because it works for me).
1

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

Comments

0

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"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.