使用映射到 C#.net 模型的 Newtonsoft.json 读取 json 的替代方法

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


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


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


PET.JSON 文件:(JSON 文件由 3rd 方提供,结构/模式与下面的示例相同,这是他们的格式 - 没有权限更改 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; }

    }

}  

Pet Reader(我需要使用映射到上述模型的这个反序列化 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


潇潇雨雨
浏览 252回答 2
2回答

宝慕林4294392

好吧,您可以改为尝试这些类,然后在 Pet 列表上循环。&nbsp; public class JsonParsed{&nbsp; &nbsp; public Dictionary<string, Attribute> Pet { get; set; }&nbsp;}public class Attribute{&nbsp; &nbsp; public bool cute { get; set; }&nbsp; &nbsp; public int feet { get; set; }}键包含宠物的名称,属性将包含其他属性。&nbsp; var json = @"{'Pet': {'Dog': {'cute': true,'feet': 4},'Bird': {'cute':&nbsp;&nbsp; false,'feet': 2}}}";&nbsp; var obj = JsonConvert.DeserializeObject<JsonParsed>(json);&nbsp;foreach (var element in obj.Pet)&nbsp;{&nbsp; &nbsp; Console.WriteLine(element.Key&nbsp; + " has " + element.Value.feet);&nbsp;}

动漫人物

我是这么想的,但我知道这是不可能的。是的,是的,可以通过以下代码实现。你必须Querying像你的 jsonstring JSON_TEXT = File.ReadAllText("PET.JSON");JObject jObject = JObject.Parse(JSON_TEXT);//This is your search termstring search = "Dog";&nbsp; //or "Bird", or "Lion", or "Tiger", or "Eagle" or anything that are present it your jsonbool cute = (bool)jObject["Pet"][search]["cute"];int feet = (int)jObject["Pet"][search]["feet"];string temp = $"My {search} is cute = {cute} and feet = {feet} ";//If you want it in your strongly type thenDog dog = jObject["Pet"][search].ToObject<Dog>();Bird bird = jObject["Pet"][search].ToObject<Bird>();输出:在上面的代码中[“宠物”] => json 的第 0 个位置级别节点。[搜索] => json 的第一个位置级别节点。["cute"] 或 ["feet"] => 你的 json 的第二个位置级别节点,还有更多你的 json 深度你可以在这里找到更多信息Querying Json
打开App,查看更多内容
随时随地看视频慕课网APP