Determine if Json results is object or array

Using Json.NET, you could do this:

string content = File.ReadAllText(path);
var token = JToken.Parse(content);

if (token is JArray)
{
    IEnumerable<Phone> phones = token.ToObject<List<Phone>>();
}
else if (token is JObject)
{
    Phone phone = token.ToObject<Phone>();
}

I found that the accepted solution using Json.NET is a bit slow for large JSON files.
It appears that the JToken API is performing too many memory allocations.
Here is a helper method that uses the JsonReader API with the same result:

public static List<T> DeserializeSingleOrList<T>(JsonReader jsonReader)
{
    if (jsonReader.Read())
    {
        switch (jsonReader.TokenType)
        {
            case JsonToken.StartArray:
                return new JsonSerializer().Deserialize<List<T>>(jsonReader);

            case JsonToken.StartObject:
                var instance = new JsonSerializer().Deserialize<T>(jsonReader);
                return new List<T> { instance };
        }
    }

    throw new InvalidOperationException("Unexpected JSON input");
}

The usage:

public HttpResponseMessage Get(string id)
{
    var filePath = $"{AssemblyDirectory}/../Data/phones/{id}.json";

    using (var json = File.OpenText(filePath))
    using (var reader = new JsonTextReader(json))
    {
        var phones = DeserializeSingleOrList<Phone>(reader);

        return Request.CreateResponse<List<Phone>>(HttpStatusCode.OK, phones);
    }
}

Tags:

C#

.Net

Json