Deserialize by automatically splitting for each element of a sublist in C#

huangapple go评论101阅读模式
英文:

Deserialize by automatically splitting for each element of a sublist in C#

问题

以下是您要求的翻译:

有可能已经存在解决这个问题的答案,但我不太知道如何解释我的问题,所以我会在这里尝试一下。

假设我从一个 JSON 格式的 API 中获取数据。假设它的格式如下:

  1. {
  2. "name": "Animals",
  3. "className": "Mammals",
  4. "speciesList": [
  5. {
  6. "species": "Panthera leo",
  7. "subspecies": "leo"
  8. },
  9. {
  10. "species": "Equus quagga",
  11. "subspecies": "quagga"
  12. }
  13. ]
  14. }

我想将它们存储在以下类中:

  1. public class Animal
  2. {
  3. public string name {get; set;}
  4. public string className {get; set;}
  5. public string species {get; set;}
  6. public string subspecies {get; set;}
  7. }

如何使用这个类进行反序列化,以便创建两个对象,如下所示:

  1. Animal("Animals", "Mammals", "Panthera leo", "leo")
  2. Animal("Animals", "Mammals", "Equus quagga", "quagga")

我知道我可以提取所有数据,但想知道是否有一种直接的方法来实现这个!提前谢谢!

英文:

It is possible that an answer to this exist but I don't really know how to explain my problem so I'll do it here.

Let's imagine I am grabbing datas from an api in a JSON format. Let's say it has the following format :

  1. {
  2. "name": "Animals",
  3. "className": "Mammals",
  4. "speciesList": [
  5. {
  6. "species": "Panthera leo",
  7. "subspecies": "leo"
  8. },
  9. {
  10. "species": "Equus quagga",
  11. "subspecies": "quagga"
  12. }
  13. ]
  14. }

And I want to store them in the following class :

  1. public class Animal
  2. {
  3. public string name {get; set;}
  4. public string className {get; set;}
  5. public string species {get; set;}
  6. public string subspecies {get; set;}
  7. }

How can I deserialize it with a class so that it creates me 2 objects, as follows :

  1. Animal("Animals", "Mammals", "Panthera leo", "leo")
  2. Animal("Animals", "Mammals", "Equus quagga", "quagga")

I know that I can extract all but wanted to know if there was a direct way to create this !
Thanks in advance !

答案1

得分: 1

使用 Newtonsoft.Json 库,首先你要将 JSON 提取为 JObject。然后将 speciesList 数组提取为 JArray,这样你可以迭代每个元素并转换为 List<Animal>

  1. using System.Linq;
  2. using System.Collections.Generic;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Linq;
  5. JObject jObj = JObject.Parse(json);
  6. List<Animal> animals = (jObj.SelectToken("speciesList") as JArray)
  7. .Select(x => new Animal
  8. {
  9. Name = jObj.Value<string>("name"),
  10. ClassName = jObj.Value<string>("className"),
  11. Species = x.Value<string>("species"),
  12. Subspecies = x.Value<string>("subspecies")
  13. })
  14. .ToList();

与此同时,建议使用 Pascal 命名法为属性命名。

  1. public class Animal
  2. {
  3. public string Name {get; set;}
  4. public string ClassName {get; set;}
  5. public string Species {get; set;}
  6. public string Subspecies {get; set;}
  7. }
英文:

With Newtonsoft.Json library, first you extract the JSON as JObject. And extract the speciesList array as JArray, so you can iterate each element and convert into List<Animal>.

  1. using System.Linq;
  2. using System.Collections.Generic;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Linq;
  5. JObject jObj = JObject.Parse(json);
  6. List<Animal> animals = (jObj.SelectToken("speciesList") as JArray)
  7. .Select(x => new Animal
  8. {
  9. Name = jObj.Value<string>("name"),
  10. ClassName = jObj.Value<string>("className"),
  11. Species = x.Value<string>("species"),
  12. Subspecies = x.Value<string>("subspecies")
  13. })
  14. .ToList();

Meanwhile, would suggest that to use Pascal case for the property name.

  1. public class Animal
  2. {
  3. public string Name {get; set;}
  4. public string ClassName {get; set;}
  5. public string Species {get; set;}
  6. public string Subspecies {get; set;}
  7. }

答案2

得分: 1

由于您想将所有代码放在一个类中,您可以考虑这样做:

  1. List<Animal> animals = JsonConvert.DeserializeObject<Animals>(json).SpeciesList;
  2. public class Animals
  3. {
  4. public List<Animal> SpeciesList { get; init; }
  5. public Animals(string name, string className, List<Animal> speciesList)
  6. {
  7. speciesList.ForEach(x =>
  8. {
  9. x.name = name;
  10. x.className = className;
  11. });
  12. SpeciesList = speciesList;
  13. }
  14. }
英文:

since you want to place all code inside of one class, you can consider this

  1. List<Animal> animals = JsonConvert.DeserializeObject<Animals>(json).SpeciesList;
  2. public class Animals
  3. {
  4. public List<Animal> SpeciesList { get; init; }
  5. public Animals(string name, string className, List<Animal> speciesList)
  6. {
  7. speciesList.ForEach(x =>
  8. {
  9. x.name = name;
  10. x.className = className;
  11. });
  12. SpeciesList = speciesList;
  13. }
  14. }
  15. </details>
  16. # 答案3
  17. **得分**: 0
  18. 你也可以使用 `JsonConvert.DeserializeObject` `JSON` 数据转换为一个 `dynamic` 对象
  19. ```csharp
  20. public class Animal
  21. {
  22. public string name {get; set;}
  23. public string className {get; set;}
  24. public string species {get; set;}
  25. public string subspecies {get; set;}
  26. }
  27. // 将 JSON 数据反序列化为 Animal 对象列表
  28. string json = "{\"name\": \"Animals\", \"className\": \"Mammals\", \"speciesList\": [{\"species\": \"Panthera leo\",\"subspecies\": \"leo\"},{\"species\": \"Equus quagga\",\"subspecies\": \"quagga\"}]}";
  29. var data = JsonConvert.DeserializeObject<dynamic>(json);
  30. List<Animal> animals = new List<Animal>();
  31. foreach (var species in data.speciesList)
  32. {
  33. Animal animal = new Animal
  34. {
  35. name = data.name,
  36. className = data.className,
  37. species = species.species,
  38. subspecies = species.subspecies
  39. };
  40. animals.Add(animal);
  41. }
  42. ```
  43. <details>
  44. <summary>英文:</summary>
  45. You can also use `JsonConvert.DeserializeObject` to convert the `JSON` data into a `dynamic` object
  46. public class Animal
  47. {
  48. public string name {get; set;}
  49. public string className {get; set;}
  50. public string species {get; set;}
  51. public string subspecies {get; set;}
  52. }
  53. // Deserialize the JSON data into a list of Animal objects
  54. string json = &quot;{ \&quot;name\&quot;: \&quot;Animals\&quot;, \&quot;className\&quot;: \&quot;Mammals\&quot;, \&quot;speciesList\&quot;: [{\&quot;species\&quot;: \&quot;Panthera leo\&quot;,\&quot;subspecies\&quot;: \&quot;leo\&quot;},{\&quot;species\&quot;: \&quot;Equus quagga\&quot;,\&quot;subspecies\&quot;: \&quot;quagga\&quot;}]}&quot;;
  55. var data = JsonConvert.DeserializeObject&lt;dynamic&gt;(json);
  56. List&lt;Animal&gt; animals = new List&lt;Animal&gt;();
  57. foreach (var species in data.speciesList)
  58. {
  59. Animal animal = new Animal
  60. {
  61. name = data.name,
  62. className = data.className,
  63. species = species.species,
  64. subspecies = species.subspecies
  65. };
  66. animals.Add(animal);
  67. }
  68. </details>

huangapple
  • 本文由 发表于 2023年5月10日 21:32:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定