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

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

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

问题

以下是您要求的翻译:

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

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

{
    "name": "Animals",
    "className": "Mammals",
    "speciesList": [
        {
            "species": "Panthera leo",
            "subspecies": "leo"
        },
        {
            "species": "Equus quagga",
            "subspecies": "quagga"
        }
    ]
}

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

public class Animal
{
   public string name {get; set;}
   public string className {get; set;}
   public string species {get; set;}
   public string subspecies {get; set;}
}

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

Animal("Animals", "Mammals", "Panthera leo", "leo")
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 :

    {
        "name": "Animals",
        "className": "Mammals",
        "speciesList": [
            {
                "species": "Panthera leo",
                "subspecies": "leo"
            },
            {
                "species": "Equus quagga",
                "subspecies": "quagga"
            }
        ]
    }

And I want to store them in the following class :

public class Animal
{
   public string name {get; set;}
   public string className {get; set;}
   public string species {get; set;}
   public string subspecies {get; set;}
}

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

Animal("Animals", "Mammals", "Panthera leo", "leo")
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>

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

JObject jObj = JObject.Parse(json);
List<Animal> animals = (jObj.SelectToken("speciesList") as JArray)
	.Select(x => new Animal
			{
				Name = jObj.Value<string>("name"),
				ClassName = jObj.Value<string>("className"),
				Species = x.Value<string>("species"),
				Subspecies = x.Value<string>("subspecies")
			})
	.ToList();

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

public class Animal
{
   public string Name {get; set;}
   public string ClassName {get; set;}
   public string Species {get; set;}
   public string Subspecies {get; set;}
}
英文:

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>.

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

JObject jObj = JObject.Parse(json);
List<Animal> animals = (jObj.SelectToken("speciesList") as JArray)
	.Select(x => new Animal
			{
				Name = jObj.Value<string>("name"),
				ClassName = jObj.Value<string>("className"),
				Species = x.Value<string>("species"),
				Subspecies = x.Value<string>("subspecies")
			})
	.ToList();

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

public class Animal
{
   public string Name {get; set;}
   public string ClassName {get; set;}
   public string Species {get; set;}
   public string Subspecies {get; set;}
}

答案2

得分: 1

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

List<Animal> animals = JsonConvert.DeserializeObject<Animals>(json).SpeciesList;

public class Animals
{
	public List<Animal> SpeciesList { get; init; }

	public Animals(string name, string className, List<Animal> speciesList)
	{
		speciesList.ForEach(x =>
		{
			x.name = name;
			x.className = className;
		});
		SpeciesList = speciesList;
	}
}
英文:

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

List<Animal> animals = JsonConvert.DeserializeObject<Animals>(json).SpeciesList;

public class Animals
{
	public List<Animal> SpeciesList { get; init; }

	public Animals(string name, string className, List<Animal> speciesList)
	{
		speciesList.ForEach(x =>
		{
			x.name = name;
			x.className = className;
		});
		SpeciesList = speciesList;
	}
}

</details>



# 答案3
**得分**: 0

你也可以使用 `JsonConvert.DeserializeObject` 将 `JSON` 数据转换为一个 `dynamic` 对象

```csharp
public class Animal
{
   public string name {get; set;}
   public string className {get; set;}
   public string species {get; set;}
   public string subspecies {get; set;}
}

// 将 JSON 数据反序列化为 Animal 对象列表
string json = "{\"name\": \"Animals\", \"className\": \"Mammals\", \"speciesList\": [{\"species\": \"Panthera leo\",\"subspecies\": \"leo\"},{\"species\": \"Equus quagga\",\"subspecies\": \"quagga\"}]}";
var data = JsonConvert.DeserializeObject<dynamic>(json);
List<Animal> animals = new List<Animal>();
foreach (var species in data.speciesList)
{
    Animal animal = new Animal
    {
        name = data.name,
        className = data.className,
        species = species.species,
        subspecies = species.subspecies
    };
    animals.Add(animal);
}
```

<details>
<summary>英文:</summary>

You can also use `JsonConvert.DeserializeObject` to convert the `JSON` data into a `dynamic` object

    public class Animal
    {
       public string name {get; set;}
       public string className {get; set;}
       public string species {get; set;}
       public string subspecies {get; set;}
    }
    
    // Deserialize the JSON data into a list of Animal objects
    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;;
    var data = JsonConvert.DeserializeObject&lt;dynamic&gt;(json);
    List&lt;Animal&gt; animals = new List&lt;Animal&gt;();
    foreach (var species in data.speciesList)
    {
        Animal animal = new Animal
        {
            name = data.name,
            className = data.className,
            species = species.species,
            subspecies = species.subspecies
        };
        animals.Add(animal);
    }

</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:

确定