【问题标题】:Using data in local document使用本地文档中的数据
【发布时间】:2018-09-04 07:10:44
【问题描述】:

我在 Visual Studio 中有一个 C# 项目,我正在使用 JSON.net,我有一个包含 5 个对象的 JSON 文件。我希望当我单击一个按钮时,来自 5 个对象的“名称”和“描述”等特定数据会出现在一个文本框中。

我不知道要使用什么方法,所以我可以访问 JSON 文件并获取其中的数据。

我在网上读到 JSON 只是一种格式化数据的方式,如果我要做查询之类的事情,我应该使用数据库。

这是 JSON 文件:

{
   "Fighter Features":{
      "Fighting Style (Archery)":{
         "name":"Fighting Style (Archery)",
         "Description:":"You gain +2 bonus to attack rolls you make with ranged weapons."
      },
      "Second Wind":{
         "name":"Second Wind",
         "Description:":"Vou have a limited well of stamina that you can draw on to protect Yourself from harm. On your turn, you can use a bonus action to regain hit points equal to ld10 + your fighter leveI."
      },
      "Fighthing Style (Defense)":{
         "name":"Fighting Style (Defense)",
         "Description:":"While you are wearing armor you gain a +1 bonus to AC."
      }
   }
}

【问题讨论】:

标签: c# json.net


【解决方案1】:

我会使用File.ReadAllText 方法来获取您计算机路径中的 JSON 数据。

string jsonData= File.ReadAllText("your file path");

然后使用 json.net JsonConvert.DeserializeObject 方法将 json 反序列化为对象。

RootObject jsonObj  = JsonConvert.DeserializeObject<RootObject>(jsonData); 

【讨论】:

    【解决方案2】:

    你可以使用它。要使用它,请使用 Newtonsoft.Json(可以作为 Nuget 包安装)。

    public partial class Welcome
    {
        [JsonProperty("Fighter Features")]
        public FighterFeatures FighterFeatures { get; set; }
    }
    
    public partial class FighterFeatures
    {
        [JsonProperty("Fighting Style (Archery)")]
        public FighthingStyleDefense FightingStyleArchery { get; set; }
    
        [JsonProperty("Second Wind")]
        public FighthingStyleDefense SecondWind { get; set; }
    
        [JsonProperty("Fighthing Style (Defense)")]
        public FighthingStyleDefense FighthingStyleDefense { get; set; }
    }
    
    public partial class FighthingStyleDefense
    {
        [JsonProperty("name")]
        public string Name { get; set; }
    
        [JsonProperty("Description:")]
        public string Description { get; set; }
    }
    
    public partial class Welcome
    {
        public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
    }
    
    public static class Serialize
    {
        public static string ToJson(this Welcome self) => JsonConvert.SerializeObject(self, Converter.Settings);
    }
    
    internal static class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters = {
                new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
            },
        };
    }
    

    【讨论】:

    • 我没有在 OP 中解释这一点,但我计划在 JSON 文件中包含 100 多个对象,不会按照您的建议进行操作使其更复杂吗?为每个对象创建类。
    【解决方案3】:

    如果我对您的理解正确,您希望像使用强类型对象一样使用 JSON 字符串。在这种情况下,来自 Json.net 的 JObject 是另一种选择。基本上 JObject 是一个递归容器,您可以递归地遍历其中的所有属性。 例如:

    void Main()
    {
        string nameOfFeature = "Second Wind";
        JObject jObject = JObject.Parse(data)["Fighter Features"] as JObject;
        foreach (JProperty feature in jObject.Properties())
        {
            if (feature.Name == nameOfFeature)
            {
                JObject secondWind = feature.Value as JObject;
                foreach (JProperty fProperty in secondWind.Properties())
                {
                    Console.WriteLine (fProperty.Name + ": " + fProperty.Value);
                }
            }
        }
    }
    

    如果您不介意更改 Json 数据结构,更简洁的方法是创建一个映射 JSON 字符串属性的强类型模型,以便您可以使用 DeserializeObject 将 JSON 字符串转换为您的 C# 模型欲望。 例如:

    void Main()
    {
        FighterFigure fighterFeature = JsonConvert.DeserializeObject<List<FighterFigure>>(data);
    }
    
    class FighterFigure
    {
        public string Name { get; set; }
        public Feature Feature { get; set; }
    }
    
    class Feature
    {
        public string Name { get; set; }
        public string Description { get; set; }
    }
    
    static string data = @"
    [
        {
            'Name': 'Fighting Style (Archery)',
            'Feature': {
                'name': 'Fighting Style (Archery)',
                'Description': 'You gain +2 bonus to attack rolls you make with ranged weapons.'
            },
        },
        {
            'Name': 'Second Wind',
            'Feature': {
                'name': 'Second Wind',
                'Description': 'You have a limited well of stamina that you can draw on to protect Yourself from harm. On your turn, you can use a bonus action to regain hit points equal to ld10 + your fighter leveI.'
            },
        },
        {
            'Name': 'Fighthing Style (Defense)',
            'Feature': {
                'name': 'Fighthing Style (Defense)',
                'Description': 'While you are wearing armor you gain a +1 bonus to AC.'
            },
        }
    ]";
    

    【讨论】:

    • 这对我有用,你认为我可以做更多具体的搜索,比如只打印以“二次风”为名称的功能吗?
    • 是的,你可以。我已经编辑了您可以在上面找到的第一种方法。但老实说,除非你只是想快速破解,否则你可以让代码永远运行。否则,将来维护动态转换的 JObject 将是一场噩梦。为每个结构创建强类型对象是一种更明智的代码管理方式。
    猜你喜欢
    • 2011-06-24
    • 2019-09-10
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2013-03-26
    • 2012-01-31
    相关资源
    最近更新 更多