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
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);
}
}