【问题标题】:Parsing JSON response in c# [closed]在 C# 中解析 JSON 响应 [关闭]
【发布时间】:2013-06-12 16:23:00
【问题描述】:

如果有帮助,我将使用 CampBX API 在我的帐户中获取资金。我编写了以下代码来进行 API 调用:

using (var wb = new WebClient())
        {
            String url = "https://CampBX.com/api/myfunds.php";

            var data = new NameValueCollection();
            data["user"] = "USERNAME";
            data["pass"] = "PASSWORD";
            var response = wb.UploadValues(url, "POST", data);
        }

WebClient.UploadValues() 返回一个byte[],我不知道如何正确解析它。

Here is the CampBX info, under Account Balances.

【问题讨论】:

    标签: c# json api post byte


    【解决方案1】:

    简单地说,您需要使用 JSON 解析器。我个人喜欢Newtonsoft.Json,这是我将在本例中使用的。

    第一步是将byte[] 转换为字符序列,可以是字符串对象,也可以是TextReader。第二步是将此信息传递给解析器。因此,在您的情况下,代码如下所示:

    JToken parsedToken;
    using (var responseReader = new StreamReader(new MemoryStream(response))) {
        parsedToken = JToken.ReadFrom(responseReader);
    }
    

    parsedToken 对象随后可用于提取您需要的任何数据。 (有关从JToken 对象中提取数据的信息,请参阅the documentation。)

    请注意,WebClient.UploadValues() 会丢弃有关响应实体字符编码的信息。 StreamReader 默认使用 UTF-8 编码,足以解析 UTF-8 或 ASCII。根据服务器使用的 JSON 编码器,响应可能始终与 ASCII 兼容,因此您可能不必担心。不过,您应该对此进行调查。

    【讨论】:

      【解决方案2】:

      DataContractJsonSerializer 内置对象将是您的朋友,前提是您知道返回对象的内部结构是什么(或者至少可以从 JSON 中猜到)。

      步骤如下: 定义一个合约类来保存反序列化的 JSON 对象

      namespace AppNameSpace  
      {
          [DataContract]              /* Place this inside your app namespace */
          internal class iResponse    /*Name this class appropriately */
          {
              [DataMember]
              internal string field1;
              [DataMember]
              internal string field2;
              [DataMember]
              internal Int32 field3;
          }
          ...
      }
      

      实际解析本身大约是三行

      DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(iOpenParams));
      MemoryStream stream1 = new MemoryStream(response);
      iResponse resp_json = (iResponse)ser.ReadObject(stream1);
      

      更多细节和示例,请参考:http://msdn.microsoft.com/en-us/library/bb412179.aspx

      【讨论】:

        【解决方案3】:

        我的解决方案更简单:

        Object retorno;
        var response = wb.UploadValues(url, "POST", data);
        using (var responseReader = new StreamReader(new MemoryStream(response))) 
        {
            retorno = JsonConvert.DeserializeObject<Object>(responseReader.ReadToEnd());
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-14
          • 1970-01-01
          相关资源
          最近更新 更多