如何使用 RestSharp 解析 JSON? [英] How to parse JSON using RestSharp?
问题描述
var client = new RestClient("http://10.0.2.2:50670/api");
var request = new RestRequest("Inventory", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
// execute the request to return a list of InventoryItem
RestResponse<JavaList<InventoryItem>> response = (RestResponse<JavaList<InventoryItem>>)client.Execute<JavaList<InventoryItem>>(request);
返回的内容是一个JSON字符串,一个对象数组.以下是它的简短摘录:
The content returned is a JSON string, an array of objects. The following is a short excerpt of it:
[{"Id":1,"Upc":"1234567890","Quantity":100,"Created":"2012-01-01T00:00:00","Category":"Tequila","TransactionType":"Audit","MetaData":"PATRON 750ML"},{"Id":2,"Upc":"2345678901","Quantity":110,"Created":"2012-01-01T00:00:00","Category":"Whiskey","TransactionType":"Audit","MetaData":"JACK DANIELS 750ML"},{"Id":3,"Upc":"3456789012","Quantity":150,"Created":"2012-01-01T00:00:00","Category":"Vodka","TransactionType":"Audit","MetaData":"ABSOLUT 750ml"}]
错误信息:
由于对象的当前状态,操作无效
Operation is not valid due to the current state of the object
这里有什么问题?我的 InventoryItem
与 JSON 字符串中的每个对象具有相同的属性.我错过了一步吗?
What is wrong here? My InventoryItem
has the same properties as each object in the JSON string. Am I missing a step?
推荐答案
我怀疑 RestSharp 中使用的 SimpleJson 无法反序列化为 JavaList.
I suspect that SimpleJson, used in RestSharp can't deserialise to a JavaList.
首先我会尝试反序列化为:
First I would try deserialising to a:
List<InventoryItem>
如果失败,我推荐 ServiceStack.Text - .Net 最快的 JSON 库;并做:
Failing that, I recommend ServiceStack.Text - .Net's fastest JSON library; and do:
var response = client.Execute(request);
var thingYouWant = JsonSerializer.DeserializeFromString<List<InventoryItem>>(response.Content);
这实际上是我自己做的.
This is actually what I do myself.
编辑(感谢评论员):在较新的版本中,这将是:
Edit (Thank you to commentators): In newer versions this would now be:
var deserializer = new JsonDeserializer();
deserializer.Deserialize<List<InventoryItem>>(response);
这篇关于如何使用 RestSharp 解析 JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!