Reputation: 21875
I have an external API that returns responses like :
{
"meta": {
"year": "...",
"month": "...",
"reasons": "...",
"api_data": "..."
},
"results": [
{
"name": "David",
"age": 43
},
{
"name": "Jason",
"age": 23
},
{
"name": "Nissan",
"age": 32
},
...
}
I want to parse only the results array , no need for the meta
proprety.
I've created an Employee class :
public class Employee
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("age")]
public int Age { get; set; }
}
And the request to the API :
public HttpResponseMessage Get(String reaction)
{
String apiUrl = "............";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
List<Employee> myObjectList = null;
var results = reader.ReadToEnd();
if (results != null)
{
dynamic data = JObject.Parse(results);
// manipulate data
// The following doesn't work since I've already parsed the data
// myObjectList = JsonConvert.DeserializeObject<List<Employee>>(data.results);
return Request.CreateResponse(HttpStatusCode.OK, myObjectList);
}
}
return Request.CreateResponse(HttpStatusCode.OK, "");
}
How can I grab all the results
array straight into a list of Employee ?
Upvotes: 1
Views: 864
Reputation: 313
Personally I advice you to : Create a class like this :
class EmployeRequestResult{
List<Employee> results;
}
As you can see, you must call the List<Employe>
in the same way as query result here is "results"
After when you get a response you can do this :
var reqResult = new JsonConvert.DeserializeObject<EmployeRequestResult>()
and to acces to employes data you just can do reqResult.results
Upvotes: 1
Reputation: 4260
You did everything right. just use data["results"]
instead of data.results
Here is the sample for your information. Using JObject
to read the results
array and using DeserializeObject
to convert the JArray to Object
var json = File.ReadAllText("json1.json");
var jObj = JObject.Parse(json);
var employees = JsonConvert.DeserializeObject<List<Employee>>(jObj["results"].ToString());
Upvotes: 2