C# Json 和 HttpWebRequest

C# Json and HttpWebRequest

我使用 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; }
}

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

例如:

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

其他选项可能是:

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

嘿,你可以下载 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();
        }
    }
}

这里有一个 link 解释了如何下载 Json.NET https://www.nuget.org/packages/newtonsoft.json/

我会用JSON.NET for this. It provides a powerful and flexible way to deserialize and consume the data (and lets you change your mind about how to do it fairly easily later). It's also available as a NuGet package.

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

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

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

如果要反序列化为 class,请创建一个:

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