我正在使用 .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;
}
上述方法可能不是最好的方法。它就是我现在的位置。
最佳答案
使用 Json.NET ,你可以这样做:
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>();
}
关于c# - 判断 Json 结果是对象还是数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20620381/