Determine if Json results is object or array

前端 未结 3 1967
借酒劲吻你
借酒劲吻你 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:46

    I found that the accepted solution using Json.NET is a bit slow for large JSON files.
    Looks like JToken API is doing too much memory allocations.
    Here is a helper method that uses JsonReader API to do the same:

    public static List DeserializeSingleOrList(JsonReader jsonReader)
    {
        if (jsonReader.Read())
        {
            switch (jsonReader.TokenType)
            {
                case JsonToken.StartArray:
                    return new JsonSerializer().Deserialize>(jsonReader);
    
                case JsonToken.StartObject:
                    var instance = new JsonSerializer().Deserialize(jsonReader);
                    return new List { 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(reader);
    
            return Request.CreateResponse>(HttpStatusCode.OK, phones);
        }
    }
    

提交回复
热议问题