c# - 判断 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>();
}

https://stackoverflow.com/questions/20620381/

相关文章:

php - 带有双引号的json解析错误

python - python中的 pretty-print json(pythonic方式)

python - 在 Python 中将 JSON 转换为字符串

ios - Swift读取远程通知的userInfo

java - Retrofit2 安卓 : Expected BEGIN_ARRAY but was

json - 如何从 nginx 生成 JSON 日志?

java - 在 Java 中将 JSON 转换为 XML

json - 将导入的 json 数据导入数据框

java - 如何将 POJO 转换为 JSON,反之亦然?

json - postman - 如何将全局变量传递到 JSON 正文