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

The returned content is a JSON string, an array of objects. The following is a brief excerpt:

[{"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"}]

Error message:

The operation is invalid due to the current state of the object

What is wrong here? Mine InventoryItemhas the same properties as every object in the JSON string. Did I miss a step?

+5
source share
2 answers

I suspect that SimpleJson used in RestSharp cannot deserialize in a JavaList.

First, I would try to deserialize a:

List<InventoryItem>

Otherwise, I recommend ServiceStack.Text -.Net the fastest JSON library; and execute:

var response = client.Execute(request);
var thingYouWant = JsonSerializer.DeserializeFromString<List<InventoryItem>>(response.Content);

This is actually what I do myself.

( ): :

var deserializer = new JsonDeserializer();
deserializer.Deserialize<List<InventoryItem>>(response);
+3

, :

var rc = new RestClient("https://api-ssl.bitly.com");
var rr = new RestRequest("/v3/link/clicks?access_token={access_token}&link={bitlyUrl}", Method.GET);

rr.AddUrlSegment("bitlyUrl", bitlyUrl);
rr.AddUrlSegment("access_token", BityAccessToken);

var response = rc.Execute(rr);
dynamic json = Newtonsoft.Json.Linq.JObject.Parse(response.Content);
var clicks = Convert.ToInt32(json.data.link_clicks.Value);
+1

All Articles