c# - 判断 Json 结果是对象还是数组

标签 c# .net json

我正在使用 .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/

相关文章:

c# - 以编程方式在 IIS 中注册 Silverlight MIME 类型

c# - 为什么这个 LINQ 表达式会破坏我的循环和转换逻辑?

c# - 我可以在调试我的应用程序时添加一些注释吗?

c# - ASP.NET 中的虚拟路径

javascript - Three.js 中 Json 格式几何的线框

ios - 如何从 Swift 4 中的描述中解析数组?

c# - 如何创建一个可以返回非空值的异步方法?

c# - 日期格式在带有 Entity Framework 的 MVC 中不起作用?

c# - .NET 反射 : how do I loop through an object that is an array type?

arrays - 使用 *ngFor (Angular 4) 遍历 JSON 对象数组