score:6

Accepted answer

not sure if this the optimum way to handle it, but you could use something like this:

if ( jsonres.selecttoken("result") is jobject )
{ ... }
else if ( jsonres.selecttoken("result") is jarray)
{ ... }
else
{ ...some exception perhaps }

edit: slight improvisation

if ( jsonres.selecttoken("result") is jobject )
{ //create jarray with the lone "result" in it }

//use the jarray 

score:0

you could create jsonconverter for that e.g.

public class singleorlistjsonconverter : jsonconverter
{
    public override bool canwrite => false;

    public override void writejson(jsonwriter writer, object value, jsonserializer serializer)
    {
        throw new notimplementedexception();
    }

    public override object readjson(jsonreader reader, type objecttype, object existingvalue, jsonserializer serializer)
    {
        var token = jtoken.readfrom(reader);
        switch (token.type)
        {
            case jtokentype.object:
                var item = token.toobject<myresulttype>();
                return new list<myresulttype>(new[] {item});
            case jtokentype.array:
                return token.toobject<list<myresulttype>>();
            default:
                return new list<myresulttype>();
        }
    }

    public override bool canconvert(type objecttype)
    {
        return objecttype == typeof(list<myresulttype>) || objecttype == typeof(myresulttype);
    }
}

and then just decorate your property with this converter

public class myclass
{
    [typeconverter(typeof(singleorlistjsonconverter))]
    public myresulttype result { get; set; }
}

i guess we could even make this converter generic, but this is just a simple example.

score:1

this is quite an old question, but i've got an answer for the system.text.json namespace in case you do not want to use the newtonsoft.json namesapce. there is also a parse method within jsondocument where you can determine the class of the root element.

var jdocument = system.text.json.jsondocument.parse(json);
if (jdocument.rootelement.valuekind == jsonvaluekind.object)
{
    //object
}

if (jdocument.rootelement.valuekind == jsonvaluekind.array)
{
    //array or list
}

score:3

this will work:

   jobject jsonres = jobject.parse(json);
   console.writeline(jsonres["result"].type);

to find out whether it's an object or array. you can use a switch-case on the enum:

            switch(jsonres["result"].type)
            {
                case jtokentype.object:
               //do something if it's an object
                    break;
                case jtokentype.array:
                //do something if it's an array
                    break;
            }

Related Query

More Query from same tag