skip to Main Content

I have to call a 3rd party API to retrieve some data. The API will return 1 of 2 response types, depending on the results of the search.

If all goes well, the API will return something similar to the following…

{
    "Items": [
        {
            "Id": "ABCD",
            "Description": "Some text here"
        },
        {
            "Id": "1234",
            "Description": "Some text here"
        }
    ]
}

However, if nothing is found or the values passed to the search are invalid, the API will return something like this…

{
    "Items": [
        {
            "Error": "2",
            "Text": "Something went wrong"
        }
    ]
}

Normally I would simply have a couple of classes that can be used to parse the JSON into a collection of values, but I do not see how I am supposed to know which classes to parse them with in advance.

Using Microsoft .NET Core/C#. At the moment, using the JSON from System.Text.Json rather than NewtonSoft but I assume that this should still be acheivable.

I have found a reference here that kind of hints at searching the response text for the word "error", but it is quite possible that will show up in the valid data and to be honest it feels like a dirty way of doing things.

2

Answers


  1. Rather than just looking for the string "Error", look for a Node named "Error".

    Given the result as a string, and classes defined to hold the successful response or error response:

    using (JsonDocument doc = JsonDocument.Parse(jsonString))
    {
        if (doc.RootElement.TryGetProperty("Items", out var itemsArr))
        {
            if (itemsArr[0].TryGetProperty("Error", out _))
            {
                // We got an error response
                ErrorResponse err = JsonSerializer.Deserialize<ErrorResponse>(json);
    
                // Handle ErrorResponse
            }
            else
            {
                // We got a success response
                SuccessResponse success = JsonSerializer.Deserialize<SuccessResponse>(json);
    
                // Handle the successful response
            }
        }
    }
    
    Login or Signup to reply.
  2. public sealed record OneOrTheOther(string Id, string Description, string Error, string Text);
    

    If your version of C# doesn’t support records, a class with the above string properties with e.g., string Id { get; init; } or string Id { get; set; } ... is an alternative.

    .NET properties that are not in the json should be left as is by deserialization, so after deserialization, determination of the disposition can be made.

    https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonunmappedmemberhandling?view=net-8.0&viewFallbackFrom=net-7.0

    Silently skips any unmapped properties. This is the default behavior.

    You may have variations on implementation/details, but this gives the general idea.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search