Someone
Someone

Reputation: 379

Parse server response in c#

I'm trying to parse a server response which is a string

{"list":["23","87","34","67","34","3"]}

This is how I'm trying to parse it, but it doesn't work.

string resultContent = response.Content.ReadAsStringAsync().Result;
var r = new JavaScriptSerializer().Deserialize<List<string>>(resultContent);

I've tried to find an example but usually json has a different structure so the examples didn't work.

Upvotes: 0

Views: 620

Answers (1)

Joshua Shearer
Joshua Shearer

Reputation: 1120

The issue is that the server response isn't actually a JSON object for a list of strings, but rather an object that has a list property, which is an array of strings.

While you could use something like Json.Net to read the data into an object that you could access procedurally, I don't know of a way to do that within the BCL.

Thus, the simplest solution is to define a class that matches the definition of the data, and deserialize it into that. If the server returns data in a variety of structures, you're probably better off using the Json.Net library I mentioned above, as creating type definitions for everything can quickly become tedious.

public sealed class ResponseModel
{
    public String[] list { get; set; }
}

Usage is the same as how you're already doing it, just replace List<string> with ResponseModel, like so:

var r = new JavaScriptSerializer().Deserialize<ResponseModel>(resultContent);

Upvotes: 3

Related Questions