Search code examples
c#jsonapigetdeserialization

How to parse out a specific named object in json in c#


I have an API endpoint that when I make a GET request returns this response

{
  "value": [
    {
      "id": 1,
      "name": "Brushcreek"
    },
    {
      "id": 2,
      "name": "Formula"
    }
  ],
  "statusCode": 200,
  "contentType": null
}

This is the code I use to make the request and attempt to parse it out

HttpResponseMessage response = await client.GetAsync("http://localhost:5000/api/Project/GetAll").ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();
                    //these three lines make sure to send a json array of the project objects to the deserializer
                    int startInd = content.IndexOf('[');
                    int endInd = content.IndexOf(']');
                    string valueThing = content.Substring(startInd, (endInd - startInd)+1);
                    Projects = JsonSerializer.Deserialize<IEnumerable<DataAccess.Models.ProjectModel>>(valueThing, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true}).ToList();
                }

What I'm trying to figure out is how can I send just the "value" Json array object into the deserializer? If I don't get the substring as I have above, I get an error from the deserializer which is due to the fact the the whole Json object does not match the format of the object it is trying to deserialize into.


Solution

  • You can use Newtonsoft. Add the using statements Newtonsoft.Json and Newtonsoft.Json.Linq and then you can get values by doing this:

    var values = JObject.Parse(content)["value"].ToObject<IEnumerable<Value>>();
    

    This assumes a Value object something like this:

    public class Value
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }