[英]Trouble deserialize JSON with RestSharp
我正在嘗試使用RestSharp反序列化來自WooCommerce的JSON響應。 我一直在這個站點上搜尋類似的帖子,但是還沒有找到任何解決方案。
我的JSON(簡體)
[
{
"id":1,
"name":"product 1",
},
{
"id":2,
"name":"product 2",
}
]
像這樣翻譯成C#:
public class ProductResponse
{
public List<Product> products { get; set; }
}
public class Product
{
public int id { get; set; }
public string name { get; set; }
}
像這樣被稱為
var response = client.Execute<ProductResponse>(request);
但這是行不通的,因為一系列產品沒有名稱。 如果JSON更改為
{
"products":
[
{
"id":1,
"name":"product 1",
},
{
"id":2,
"name":"product 2",
}
]
}
它像一種魅力。 不幸的是,我無法更改JSON格式。 那么我該如何解決呢?
提前致謝
您可以注釋您的產品類,以告訴RestSharp哪個屬性是哪個:
public class Product
{
[DeserializeAs(Name = "id")]
public int id { get; set; }
[DeserializeAs(Name = "name")]
public string name { get; set; }
}
然后:
var response = client.Execute<List<Product>>(request);
現在,您應該具有一個List<Product>
其中包含兩個正確填充的條目。
后代的原始答案:
我還沒有RestSharp的答案(但是),但是如果可以使用Newtonsoft JSON可以輕松實現。
您可以這樣使用JsonProperty批注:
public class Product
{
[JsonProperty("id")]
int id { get; set; }
[JsonProperty("name")]
string name { get; set; }
}
然后:
var products = JsonConvert.DeserializeObject<List<Product>>(json);
我認為您的反序列化實際上應該是List<Product>
而不是ProductResponse
。
例如
var response = client.Execute<List<Product>>(request);
Console.WriteLine("id = " + response[0].id) // id = 1
Console.WriteLine("name = " + response[0].name) // name = product 1
Console.WriteLine("id = " + response[1].id) // id = 2
Console.WriteLine("name = " + response[1].name) // name = product 2
因此,JSON字符串沒有任何問題,我認為問題是您正在期待一個ProductResponse
類型的對象,其中,當您的JSON字符串是一個Product
類型的數組/列表時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.