【发布时间】:2013-12-16 20:36:08
【问题描述】:
我正在使用 .net web api 来获取 json 并将其返回到前端以获取角度。 json 可以是对象或数组。我的代码目前仅适用于数组而不是对象。我需要找到一种方法来尝试解析或确定内容是对象还是数组。
这是我的代码
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;
}
上述方法可能不是最好的方法。它就是我现在的位置。
【问题讨论】: