确定的Json结果是对象或数组 [英] Determine if Json results is object or array

查看:139
本文介绍了确定的Json结果是对象或数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的.NET Web API来获取JSON,并返回到了角前端。的JSON可以是一个对象或一个数组。我的代码目前仅适用于数组而不是对象。我需要找到一种方法来的TryParse或确定是否内容是一个对象或数组。

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.

下面是我的代码

    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.

推荐答案

使用的 Json.NET ,你可以这样做:

Using Json.NET, you could do this:

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

这篇关于确定的Json结果是对象或数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆