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

本文关键字:Json 读取 和解 | 更新日期: 2023-09-27 18:04:53

我正在尝试解析包含大量对象的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; }
            }

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

你可以这样做,把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,我已经有了类似的答案这个问题在这里你可以检查如何轻松创建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;