Home > OS >  .NET custom Json converter for list or single item
.NET custom Json converter for list or single item

Time:09-24

my goal is to use System.text.Json to parse a response from the rest api. The response returns one or more items - but if only one item is returned, there are no brackets [] surrounding it (which makes it hard to parse).

The deserialization:

// i need a list here to process data
var response = JsonSeralizer.Deseralize<IList<ExampleResponse>>(content);

Example response 1:

[
 {
  "Status": "Healthy"
 },
 {
  "Status": "Healthy"
 }
]

Example response 2:

{
 "Status": "Healthy"
}

How can i write a custom converter using JsonConverter<T>, which can parse a single item or an entire list?

CodePudding user response:

If you cannot change the output of the REST API to force it to always return an array, you can check the string before parsing it, and add brackets. Then parse it.

I made this example: https://dotnetfiddle.net/dhZIKq

CodePudding user response:

One option is to create a custom converter (inherit from JsonConverter)

Though with this case I would've probably just wrote

var isList = content.StartsWith("[");
var response = isList ? JsonSeralizer.Deseralize<IList<ExampleResponse>>(content)
 : new IList<ExampleResponse> { JsonSeralizer.Deseralize<ExampleResponse>(content) };

CodePudding user response:

You can check if content starts with '{' in that case Deserialize to Single item and after that create new List from the single item.

List<ExampleResponse> response;
if (content.StartsWith("{"){
   response = new List<ExampleResponse>(){
               JsonSerilizer.Deserialize<ExampleResponse>(content)
             };
else
{
    response = JsonSeralizer.Deseralize<IList<ExampleResponse>>(content);
}
  • Related