【问题标题】:C# Json and HttpWebRequestC# Json 和 HttpWebRequest
【发布时间】:2015-11-16 15:00:30
【问题描述】:

我使用HttpWebRequest 从网站获取内容。 问题是我得到了 json 的响应,但我真的不知道如何在我的程序中使用、转换和实现该数据。

当前代码:

namespace Web_Scraper
{
    class Program
        {
            static void Main(string[] args)
            {

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();


                StreamReader stream = new StreamReader(response.GetResponseStream());


                string final_response = stream.ReadToEnd();



                Console.WriteLine("Genuine Purity Fist");
                Console.WriteLine(final_response);
                Console.ReadKey();
        }
    }
}

回复:

{"success":true,"lowest_price":"1,05\u20ac","volume":"26","median_price":"1,06\u20ac"}

json2csharp 代码:

public class RootObject
{
    public bool success { get; set; }
    public string lowest_price { get; set; }
    public string volume { get; set; }
    public string median_price { get; set; }
}

【问题讨论】:

    标签: c# json steam


    【解决方案1】:

    你可以下载 Json.NET 并像这样解析你的 json 字符串:

     using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
    
                StreamReader stream = new StreamReader(response.GetResponseStream());
    
    
                var final_response = stream.ReadToEnd();
    
                // Converts the unicode to string correctValue.
    
    
                string correctValue = "Euro";
                StringBuilder sb = new StringBuilder(final_response);
                if (sb.ToString().Contains("\\u20ac"))
                {                
                    sb.Replace("\\u20ac", correctValue);
                }            
    
                dynamic items = JObject.Parse(sb.ToString());
    
                bool success = items.success;
                string lowest = items.lowest_price;
                string volume = items.volume;
                string median = items.median_price;            
    
                // Create a test object of RootObject class and display it's values in cw.
                RootObject r = new RootObject(success, lowest, volume, median);
                Console.WriteLine("TEST OBJECT VALUES: Success: " + r.success + ", lPrice: " + r.lowest_price + ", vol: " + r.volume + ", mPrice: " + r.median_price + "\n");
    
                // Calculation example
                double num1 = Convert.ToDouble(r.FixComma(r.lowest_price,correctValue));
                double num2 = Convert.ToDouble(r.FixComma(r.median_price, correctValue));
                double result = num1 + num2;
                Console.WriteLine("Result: " + result+"\n");
    
                Console.WriteLine("Genuine Purity Fist");
                Console.WriteLine(final_response);
                Console.ReadKey();            
            }
        }
    
        public class RootObject
        {
            public bool success { get; set; }
            public string lowest_price { get; set; }
            public string volume { get; set; }
            public string median_price { get; set; }
    
            public RootObject(bool success, string lowest_price, string volume, string median_price)
            {
                this.success = success;
                this.lowest_price = lowest_price;
                this.volume = volume;
                this.median_price = median_price;
            }
    
            public string FixComma(string value,string currency)
            {
                string correctValue = ".";
                string correctValue2 = "";
                StringBuilder sb = new StringBuilder(value);
                if (sb.ToString().Contains(","))
                {
                    sb.Replace(",", correctValue);
                }
                if (sb.ToString().Contains(currency))
                {
                    sb.Replace(currency, correctValue2);
                }
                return sb.ToString();
            }
        }
    }
    

    这是一个解释如何下载 Json.NET https://www.nuget.org/packages/newtonsoft.json/ 的链接。

    【讨论】:

    • 两个RootObject有两个错误,如果可能的话还想对代码做一点解释。
    • 你在你的 RootObject 类中添加了一个构造函数吗?
    • 在 rootobject 类中添加了构造函数,并在 Main 中进行了测试,在那里我创建了一个 RootObject,然后将其打印出来。
    • 我只是复制了你的代码,我没有做任何其他事情,我得到“类型或命名空间名称'RootObject'...”
    • 嘿,现在尝试复制它 我编辑了它,所以它显示了整个代码,而不仅仅是它的一部分。
    【解决方案2】:

    一种选择是使用System.Web.Script.Serialization 命名空间中的JavaScriptSerializer 类。

    例如:

    RootObject obj = new JavaScriptSerializer().Deserialize<RootObject>(final_response);
    

    其他选项可能是:

    • 自己使用反射或手动解析。
    • this one 等第三方库。

    【讨论】:

    • 感谢您的快速回复,我会看看我能用这个做什么。
    • 好吧,真的不明白我应该做什么。我应该把这段代码放在哪里? JavaScriptSerializer 也出现错误。
    • 将此代码放在string final_response 下 - 您在使用JavaScriptSerializer 时遇到什么错误?
    • 好吧,当我得到最少的错误时,我有一个错误,但不记得是什么了。顺便说一句,我应该用 json2csharp 代码创建一个新类,还是把它放在你的代码上方?我在 google 上看到了多种变体,我不确定我应该怎么做。
    • 是的。添加json2csharp给你的代码,然后你就可以创建所需的对象了。
    【解决方案3】:

    我会为此使用JSON.NET。它提供了一种强大而灵活的方式来反序列化和使用数据(并让您在以后轻松地改变主意)。也可以使用as a NuGet package

    最简单的方法是将其反序列化为dynamicObject 实例:

    var object = JsonConvert.Deserialize<Object>(final_response);
    var isSuccessful = object.success; // true or false
    // ...
    

    (您也可以将object 替换为dynamic。)

    如果你想反序列化为一个类,创建一个:

    class PriceData {
      public bool success { get; set; }
      public string lowest_price { get; set; }
      public string  volume { get; set; }
      public string median_price { get; set; }
    }
    

    然后改为拨打.Deserialize&lt;PriceData&gt;(final_response)

    如果你不喜欢用小写或下划线命名的变量(这在 C# 中不是常用的样式),你可以重写反序列化来指定哪个字段用于哪个 C# 属性:

    class PriceData {
      [JsonProperty("success")]
      public bool Success { get; set; }
    
      [JsonProperty("lowest_price")]
      public string LowestPrice { get; set; }
    
      [JsonProperty("volume")]
      public string  Volume { get; set; }
    
      [JsonProperty("median_price")]
      public string MedianPrice { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-07
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      相关资源
      最近更新 更多