Home > front end >  Deserialsie JsonConvert.DeserializeObject array but can have one object
Deserialsie JsonConvert.DeserializeObject array but can have one object

Time:01-26

I have am consuming some survey data via JSON from an API for my .Net app. I have created a class from the JSON file in my .net app. The JSON has a node called Response[] which is an array - so my survey platform gives me back multiple surveys. This works great when I get two or more surveys back (as its an array).

var root = JsonConvert.DeserializeObject<SurveyJsonModel.Rootobject>(json);

However, if the survey platform only returns back one survey the deserialisation fails, I suspect as the JSON is not returning an array. See attached screen shot of my model that I have created from the JSON. Any idea how I resolve - so it works for one record as well as multiples? Also not fail for zero records eithier. I suspect my model needs chnaging or do I need to use a different deserialisation method

TIAenter image description here

The error message I get is:

Please see below the error message:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'SurveyJsonModel Response[]' because the type requires a JSON array(e.g. [1, 2, 3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1, 2, 3]) or change the deserialized type so that it is a normal .NET type (e.g.not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

CodePudding user response:

If you are using .NET Core 3 or higher you can try to change the type of the Response property to JsonElement and check the ValueKind property to see if it is an object or an array.

CodePudding user response:

You don't need any custom converters, in this case I usually recommend to create a very simple JsonConstructor

public partial class Rootobject
{
    // ... all class properties

    [JsonConstructor]
    public Rootobject(JToken Responses)
    {
        if (Responses.GetType().Name == "JArray")
            this.Responses = Responses.ToObject<<Response[]>>();
        else
            this.Responses = new Response[] { Responses };
    }
    public Rootobject() { }
}
  • Related