在c#上读取并解析Json并获取特定值

时间:2016-08-31 15:56:27

标签: c# .net json json.net

我正在尝试解析包含大量对象的Json。

.json看起来像这样: :

{
  "status" : "success",
  "prices" : [
    {
      "market_hash_name" : "4X4 Car",
      "price" : "7.87",
      "created_at" : 1472587613
    },
    {
      "market_hash_name" : "Yellow Car",
      "price" : "27.75",
      "created_at" : 1472519899
    }

[...]等

我只想获得特定市场哈希名称的价格。我怎么能这样做?

我有这个atm

using System.IO;
using Newtonsoft.Json;
      public class MarketHandler
        {
            //Methods
            public MarketHandler updatePrices()
            {
                var json = File.ReadAllText("PriceSkins.json");
                currentPrices = JsonConvert.DeserializeObject<Data>(json);
                return this;
            }

            public Data currentPrices { get; set; }
            public class Data
            {
                public Response response { get; set; }
            }

            public class Response
            {
                public string status { get; set; }
                public Price prices { get; set; }
            }

            public class Price
            {
                public string market_hash_name { get; set; }
                public string price { get; set; }
                public int created_at { get; set; }
            }

1 个答案:

答案 0 :(得分:0)

您可以这样做,将JSON放在系统上的其他位置并加载JSON,如下所示

 Rootobject ro = new Rootobject();
 StreamReader sr = new StreamReader(Server.MapPath("text.json"));
 string jsonString = sr.ReadToEnd();
 JavaScriptSerializer ser = new JavaScriptSerializer();
 ro = ser.Deserialize<Rootobject>(jsonString);

在此之前你必须创建如下所示的类,这些类与你的JSON匹配,我已经轻易回答了类似的问题here you can cehck how to create classes for JSON

public class Rootobject
{
    public string status { get; set; }
    public Price[] prices { get; set; }
}

public class Price
{
    public string market_hash_name { get; set; }
    public string price { get; set; }
    public int created_at { get; set; }
}

之后,从Rootobject(ro)的实例中,您可以访问以下价格

Price[] price_list = ro.prices;