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 the object. I need to find a way to tryparse or determine if the contents are an object or array.
Here is my code
public HttpResponseMessage Get(string id)
{
string singleFilePath = String.Format("{0}/../Data/phones/{1}.json", AssemblyDirectory, id);
List<Phone> phones = new List<Phone>();
Phone phone = new Phone();
JsonSerializer serailizer = new JsonSerializer();
using (StreamReader json = File.OpenText(singleFilePath))
{
using (JsonTextReader reader = new JsonTextReader(json))
{
//if array do this
phones = serailizer.Deserialize<List<Phone>>(reader);
//if object do this
phone = serailizer.Deserialize<Phone>(reader);
}
}
HttpResponseMessage response = Request.CreateResponse<List<Phone>>(HttpStatusCode.OK, phones);
return response;
}
The above may not be best way of doing this. Its just where I am now.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…