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

Time:09-17

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.

CodePudding user response:

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

CodePudding user response:

I think you should just create a response class:

public class Response
{
    public List<DataAccess.Models.ProjectModel> value {get;set;}
    public Int32 statusCode {get;set;}
    public String contentType {get;set;}
}

And deserialize into that:

Projects = JsonSerializer.Deserialize<Response>(content).value;

CodePudding user response:

One way you could do this using NewtonSoft, I don't think there is a elegant way to do this in using System.Text.Json as of yet(at least not that I am aware of).

https://www.newtonsoft.com/json/help/html/SelectToken.htm

If your getting deserializer issues and dont want to use a strongly typed object or it will changed then you can use dynamic type as well.

Not ideal I know, but its a solution.

  • Related