[英]Deserialize json array to c# list object
I am trying to parse a JSON response from a service to c# observation collection list object.我正在尝试解析从服务到 c# 观察集合列表对象的 JSON 响应。 The list object later can be used to showcase on the XAML page.稍后可以使用列表对象在 XAML 页面上进行展示。
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.在尝试对将 JSON 数组反序列化为 c# 进行一些更改后,我无法成功。 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.我在这个问题上坚持了很长时间,在 StackOverflow 上搜索并在谷歌上搜索,但没有富有成效的解决方案。
I need to store the JSON data into ac# object and reproduce the same object in the XAML page as a list.我需要将 JSON 数据存储到 ac# 对象中,并将 XAML 页面中的相同对象作为列表重现。
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.我确定该异常与您的 JSON 字符串无关,但尝试从解决方案文件夹中删除bin
和obj
,然后清理并重建解决方案。
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.....无法将当前 JSON 数组(例如 [1,2,3])反序列化为“namespace.Order”类型,因为该类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化.....
Because your JSON string is List of Order
so the deserialize would be change to :因为您的 JSON 字符串是Order
列表,所以反序列化将更改为:
List<Order> ObjOrderList = JsonConvert.DeserializeObject<List<Order>>(orderJson);
or in the other side you can also use JavaScriptSerializer
like:或者在另一方面,您也可以使用JavaScriptSerializer
例如:
Order[] orderList = new JavaScriptSerializer().Deserialize<Order[]>(orderJson);
Your JSON starts with a [
and ends with a ]
.您的 JSON 以[
开头并以]
结尾。 This means that your JSON represents an array of objects.这意味着您的 JSON 表示一个对象数组。 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
).在您的潜意识中,您知道它,实际上您的反序列化变量的名称是ObjOrderList
(突出显示List
)。
So, just deserialize to an array/list of Order
.因此,只需反序列化为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.代码是使用QuickType.io生成的,我丢弃了转换器和其他一些额外的类。 You can change the Long type to int if you want.如果需要,您可以将 Long 类型更改为 int。
To use it just call要使用它只需调用
var orderResponse = OrderResponse.FromJson(jsonString);
pass the response instead of jsonString传递响应而不是 jsonString
In this Code you can DeserializeObject
json file:在此代码中,您可以DeserializeObject
json 文件:
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: jsonVariables
类是:
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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.