【问题标题】:Parsing complex JSON text with Json.NET使用 Json.NET 解析复杂的 JSON 文本
【发布时间】:2014-05-27 14:23:55
【问题描述】:

我正在编写一个程序来访问 Mediafire 的 Web API,一切顺利,唯一剩下的问题是我难以解析的 JSON 格式的响应文本。

通过创建文件夹等 API 调用,我得到一个简单的响应,可以将其反序列化为 Dictionary<string,Dictionary<string,string>> 并搜索值:

{"response":
    {
    "action":"folder\/create.php",
    "name":"blargh",
    "folder_key":"mmttuu769djo0",
    "result":"Success",
    "current_api_version":"2.14"
    }
}

我会这样使用它:

Dictionary<string,string> json = DeserializeJSON(text)["response"];
//DeserializeJSON is a method to shorten:
//JsonConvert.DeserializeObject<Dictionary<string,Dictionary<string,string>>(text)

然后我可以查询 json["result"] 之类的。通过其他 API 调用,我得到了我不知道如何处理的复杂结构。它基本上是一堆键:值对,但有些值也是键:值对,不能像我目前正在做的那样放入字典中。我对 C# 还很陌生,所以我不确定在这里做什么,是否还有其他数据类型,例如没有静态类型的 Dictionary?

回复如下:

{"response":
    {
    "action":"upload\/upload.php",
    "doupload":
        {
        "result":"0",
        "key":"89lh7760x4l"
        },
    "server":"live",
    "result":"Success",
    "current_api_version":"2.14"
    }
}

我的问题是:将此类数据放入可以查询值的列表中的好方法是什么?

【问题讨论】:

  • 不要在问题中写下你自己的答案,这样阅读的人可能会找到“正确答案”
  • 当时我试过了,但有些警告说我必须等待 8 小时才能回答我自己的问题,不过我现在看看能不能做到。是的,但现在我必须等待 24 小时才能接受!

标签: c# json dictionary json.net


【解决方案1】:

我最终发现了 dynamic 类型 - 将文本反序列化为 Dictionary&lt;string,dynamic&gt; 允许它具有多种类型,其中一些也可以是字典。我可以按预期查询它,但我只需要确定每个 API 调用返回什么值,并且需要将其转换为字符串。

string upload_key = (string)json["response"]["doupload"]["key"] //89lh7760x4l

【讨论】:

    【解决方案2】:

    创建一个新类来处理 json 怎么样?您可以使用示例 json 使用 json2csharp 生成类。

    public class Doupload
    {
        public string result { get; set; }
        public string key { get; set; }
    }
    
    public class Response
    {
        public string action { get; set; }
        public Doupload doupload { get; set; }
        public string server { get; set; }
        public string result { get; set; }
        public string current_api_version { get; set; }
    }
    
    public class RootObject
    {
        public Response response { get; set; }
    }
    

    然后您可以使用以下方法对 json 进行反序列化:

    JavaScriptSerializer serializer = new JavaScriptSerializer(); 
    var something = serializer.Deserialize<RootObject>(jsonString);
    

    【讨论】:

    • 嗯...这似乎是一个很好的方法,但大多数 API 调用都有唯一的键,所以我必须为每个 API 函数创建一个类。
    • 这对我来说听起来是个好主意,我更喜欢强类型版本。你真的需要创建多少个类?
    • 大约有 50-60 个不同的 API 函数可供访问,您可以在此处查看其中一些函数的响应:mediafire.com/developers 我想我需要为每个函数创建一个类,但我不确定.
    猜你喜欢
    • 1970-01-01
    • 2010-09-28
    • 2014-03-05
    • 2014-11-19
    • 2017-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多