Determine if Json results is object or array

前端 未结 3 1973
借酒劲吻你
借酒劲吻你 2020-12-05 06:02

I am using .net web api to get json and return it to the front end for angular. The json can be either an object or an array. My code currently only works for the array not

3条回答
  •  余生分开走
    2020-12-05 06:50

    Asthetically I like the answer @dcastro gave better. But, if you are generating a JToken object, you can also just use the Type enum property of the token. It's possibly less expensive then doing an object type comparison, as the Type property has already been determined.

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

    //...JToken token
    if (token.Type == JTokenType.Array)
    {
        IEnumerable phones = token.ToObject>();
    }
    else if (token.Type == JTokenType.Object)
    {
        Phone phone = token.ToObject();
    }
    else
    {
        Console.WriteLine($"Neither, it's actually a {token.Type}");
    }
    

提交回复
热议问题