【问题标题】:Read and parse Json on c# and get specific values在 c# 上读取和解析 Json 并获取特定值
【发布时间】:2016-08-31 15:56:27
【问题描述】:

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

[...] 等

我只想获取特定市场哈希名称的价格。我该怎么做?

我有这个自动取款机

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

【问题讨论】:

  • 那么问题出在哪里?另外,我没有看到您实际尝试获取值的代码。
  • 您的模型目前与您的 JSON 不匹配 - 您没有 single 价格,您有一个 array 价格。 (我敦促您遵循 .NET 命名约定并使用属性来指定 JSON 表示,顺便说一句。)

标签: c# .net json json.net


【解决方案1】:

您可以这样做,将您的 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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2017-02-23
    • 1970-01-01
    • 2012-10-29
    相关资源
    最近更新 更多