【问题标题】:Can you help me parse this JSON?你能帮我解析这个 JSON 吗?
【发布时间】:2021-01-28 22:48:53
【问题描述】:

我有一个 C# 应用程序,它从数据包中读取玩家库存(项目名称 + 项目 ID + 项目计数)。我找到了一个网站,我可以在其中找到商品名称 + 数量/价格,但它是 json 格式:

"AI Brain": {
  "qty":15,
  "price":1
},
"Air Conditioner": {
  "qty":190,
  "price":1
}

所以现在我在我的检查器中跟踪了玩家库存并获得了项目名称。我需要使用json格式来获取商品的数量和价格。我怎样才能做到这一点?有很多东西...

【问题讨论】:

  • 你检查过一些 C# JSON 库了吗?
  • 是的,我做了,但很难理解,还有 AI BRAIN 然后对象 idk 如何解析它
  • 你确定这是你得到的json格式吗?通常,您的价值“AI BRAIN”应该分配给一个属性,例如。名称
  • 如果你在你显示的字符串周围加上大括号"{AI Brain: {... etc... "price" : 1}}",那么你显示的是一个JSON对象,带有to属性(AI BrainAir Conditioner}每个都是对象值,这两个对象每个都有两个属性(一个名为 qty 的数字和一个名为 price 的数字)。加上大括号,任何 JSON 解析器都应该能够反序列化它跨度>
  • 您得到的任何答案对您有帮助吗?至少,您需要在 JSON 字符串的末尾添加 "{" 并添加 "}" 以使其成为正确的 JSON。除此之外,只需以某种方式将 JSON 反序列化到内存中

标签: c# json .net parsing


【解决方案1】:

查看https://json2csharp.com/https://jsonlint.com/ 主要问题是这是一个可怕的设计,因为每个项目名称都变成了一个新类,而不是你想要的是下面的东西,哪个封装和项目,以及@Flydog57 所说的内容

    {
       "Name": "AI Brain",
        "Properties": {
          "qty": 15,
          "price": 1
        }
    },
    {
       "Name": "Air Conditioner",
        "Properties": {
          "qty": 190,
          "price": 1
        }
    }

c#

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    public class Properties    {
        public int qty { get; set; } 
        public int price { get; set; } 
    }

    public class Root    {
        public string Name { get; set; } 
        public Properties Properties { get; set; } 
    }

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
    public class AIBrain    {
        public int qty { get; set; } 
        public int price { get; set; } 
    }

    public class AirConditioner    {
        public int qty { get; set; } 
        public int price { get; set; } 
    }

    public class Root    {
        public AIBrain AIBrain { get; set; } 
        public AirConditioner AirConditioner { get; set; } 
    }

【讨论】:

  • 或者...您可以定义一个具有两个int 属性(qtyprice)的类,我们将其称为Item,然后将其反序列化为Dictionary&lt;string, Item&gt;跨度>
  • @Flydog57:确实是一个不错的选择
【解决方案2】:

另一种方法是将其反序列化为字典。这里我使用的是 NewtonSoft JSON Nuget 包。

首先创建一个类,定义每个项目的属性:

public class TestItem
{
    public int qty { get; set; }
    public int price { get; set; }
}

然后将其反序列化为字典。请注意,您可以在 Javascript(以及 JSON)中使用单引号或双引号。我在这里使用单引号而不是双引号 - 它使代码更清晰。另请注意,我添加了一个前导 { 和一个尾随 } 以将您的字符串转换为合法的 JSON:

 public static void Deserialize()
 {
     var someJson = "{'AI Brain':{ 'qty':15,'price':1},'Air Conditioner':{ 'qty':190,'price':1}}";
     var results = JsonConvert.DeserializeObject<Dictionary<string, TestItem>>(someJson);
 }

这样的结果是一个包含两个项目的字典,每个项目都有一个string Key 和一个TestItem Value

如果您正在从文件中读取该数据,则可以不理会引号,只需在读取字符串后将"{" 连接到开头,将"}" 连接到结尾。像这样:

 var fileContents = File.ReadAllText("TestItem.json");
 var fileJson = "{" + fileContents + "}";
 var resultsFromFile = JsonConvert.DeserializeObject<Dictionary<string, TestItem>>(fileJson);

(假设您显示的 JSON 在名为 "TestItem.json" 的文件中)

这是反序列化对象在调试器中的样子:

【讨论】:

  • 我会赞成其中一些,因为 OP 似乎已经放弃了这一点。
【解决方案3】:

如果您不想创建类(顺便说一句,这是一个很好的做法),您可以使用动态和 Newtonsoft.json 包:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            //note: needed to fix json here
            var json = @"{""AI Brain"":{ ""qty"":15,""price"":1},""Air Conditioner"":{ ""qty"":190,""price"":1}}";
 
            //note2: dynamic is tricky and sensitive for typos.
            dynamic obj = JObject.Parse(json);
 
            //if you know what you want upfront, you can just do
            //Console.WriteLine(obj["AI Brain"].qty);
            //you can also loop them like this:
            foreach (var pair in obj)
            {
                Console.WriteLine(pair.Name);

                Console.WriteLine(obj[pair.Name].qty);
                Console.WriteLine(obj[pair.Name].price);
            }
        }
    }
}

输出:

AI Brain
15
1
Air Conditioner
190
1

【讨论】:

    【解决方案4】:

    您可以使用 Newtonsoft.Json、动态和属性发现来做这样的事情:

    using Newtonsoft.Json;
    
    //...
    
    var json = "{'AI Brain':{ 'qty':15,'price':1},'Air Conditioner':{ 'qty':190,'price':1}}";
    
    dynamic obj = JsonConvert.DeserializeObject(json);
    
    foreach(var property in obj.Properties())
        Console.WriteLine($"{property.Name}: {property.Value.qty} @ {property.Value.price:c}");
    

    【讨论】:

      猜你喜欢
      • 2017-12-23
      • 1970-01-01
      • 2021-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多