首页 > 解决方案 > 使用映射到 C#.net 模型的 Newtonsoft.json 读取 json 的替代方法

问题描述

很抱歉没有为我的主题提供最佳/合适的标题,如果您有比我更好的标题,将很高兴更新它。

我当前的问题是我必须处理使用 Newtonsoft.JSON 从 .JSON 文件读取 json 的现有代码(从 3rd 方源提供)。它也映射到现有类。我不确定这是否是通过执行 IF-ELSE 来获得正确的 json 节点的正确方法,也许有人会有其他选择/比我更好的方法。谢谢你。

这不是确切的代码,但我复制了与我的问题相关的代码。

PET.JSON 文件:(JSON 文件由第 3 方提供,结构/模式与下面的示例相同,此后一直是他们的格式-不允许更改 JSON 格式)

{
  "Pet": {
    "Dog": {
      "cute": true,
      "feet": 4
    },
    "Bird": {
      "cute": false,
      "feet": 2
    }
  }
}  

宠物类和子类(这是第 3 方标准结构,我无权修改它)

public class Pet
{
    public Dog dog { get; set; }
    public Bird bird { get; set; }

    public class Dog {
        public bool cute { get; set; }
        public int feet { get; set; }
    }

    public class Bird
    {
        public bool cute { get; set; }
        public int feet { get; set; }
    }
}  

宠物阅读器(我需要使用这个反序列化的 Json 对象映射到上面的模型,没有权限修改他们的实现“还”我必须自己管理如何使用 ReadPetJSON() 的返回值)

public static Pet ReadPetJSON()
{
    string JSON_TEXT = File.ReadAllText("PET.JSON");
    Pet pet = Newtonsoft.Json.JsonConvert.DeserializeObject<Pet>(JSON_TEXT);
    return pet;
}  

更新:我发现了使用反射,我可以传递一个变量名来查找 PropertyName。谢谢大家的帮助和投入,我很感激

http://mcgivery.com/c-reflection-get-property-value-of-nested-classes/

// Using Reflection
Pet pet = ReadPetJSON();

// Search Bird > feet using 'DOT' delimiter
string searchBy = "bird.feet"

foreach (String part in searchBy.Split('.'))
{
    if (pet == null) { return null; }

    Type type = pet.GetType();
    PropertyInfo info = type.GetProperty(part);
    if (info == null) { return null; }  // or make a catch for NullException

    pet = info.GetValue(pet, null);
}

var result = pet.ToString(); // Object result in string
Console.WriteLine("Bird-Feet: {0}", result);

输出:

Bird-Feet: 2

标签: c#jsonjson.net

解决方案


好吧,你可以试试这些类,然后在宠物列表上循环。

  public class JsonParsed
{
    public Dictionary<string, Attribute> Pet { get; set; } 
}

public class Attribute
{
    public bool cute { get; set; }
    public int feet { get; set; }
}

键包含宠物的名称,属性将包含其他属性。

  var json = @"{'Pet': {'Dog': {'cute': true,'feet': 4},'Bird': {'cute': 
  false,'feet': 2}}}";
  var obj = JsonConvert.DeserializeObject<JsonParsed>(json);
 foreach (var element in obj.Pet)
 {
    Console.WriteLine(element.Key  + " has " + element.Value.feet);
 }

推荐阅读