简体   繁体   English

数组 Json C# 中的反序列化问题

[英]Array Json Deserialization Issues in C#

string uri = Application.Current.Properties["Uri"].ToString();
var client = new HttpClient();
var result = await client.GetAsync(uri + "/products");
var resultparsing = JsonConvert.DeserializeObject<ProductResponse>(await 
result.Content.ReadAsStringAsync());
var list = JsonConvert.DeserializeObject<List<Item>>(resultparsing.products.ToString());

The code running, Deserialization issue coming from listtostring when the resultparsing is passing just the object name which in this case it just saying it is a list and not passing the list itself to var list when it attempts to fetch the items.代码运行时,当结果解析仅传递 object 名称时,反序列化问题来自 listtostring,在这种情况下,它只是说它是一个列表,而不是在尝试获取项目时将列表本身传递给 var 列表。

public class Item
    {
        public string _id { get; set; }
        public string name { get; set; }
        public string location { get; set; }
    }
    public class ProductResponse
    {
        public string count { get; set; }
        public List<Item> products { get; set; }
    }

Examples of Json that is initially being captured最初被捕获的 Json 的示例

{"count":2,"products":[{"name":"item","location":"storeroom","_id":"6219602068c9a900043fe844"},{"name":"item2","location":"storeroom","_id":"6219603768c9a900043fe850"}]}

you only need to deserialize once你只需要反序列化一次

var json = await result.Content.ReadAsStringAsync();
var resp = JsonConvert.DeserializeObject<ProductResponse>(json);

resp is a ProductResponse object that should contain all of the product detail in the products property. respProductResponse object,它应该包含products属性中的所有产品详细信息。 You do not need to deserialize products separately您不需要单独反序列化产品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM