gpt4 book ai didi

c# - 将 JSON 转换为 C# 数组

转载 作者:行者123 更新时间:2023-12-03 19:29:04 26 4
gpt4 key购买 nike

我是 C# 的新手,遇到了一些小问题。我有一个包含一些邮件地址的 JSON 文件。对于每个邮件地址,此 JSON 文件中有 4 个字段(名称、电子邮件 []、印记、信息 2)。我想在我的项目中将其转换为数组或数组列表,我目前正在使用 Newtonsoft.Json 来实现此目的。

我做了一个类(class)地址:

public class adress
{
public string name = "";
public string[] email = {""};
public string imprint = "";
public string info2 = "";
}

这是 json:

{"name":"test1","email":["test1@test.de"],"imprint":"testimprint1 testimprint1","info2":"testinfo1"} {"name":"test2","email":["test2@test.de"],"imprint":"testimprint2 testimprint2","info2":"testinfo2"} {"name":"test3","email":["test3@test.de"],"imprint":"testimprint3 testimprint3","info2":"testinfo3"}

并尝试像这样转换它:

List<adress> adresses = new List<adress>();
string json_adress = File.ReadAllText("C:\\Mail\\adresses.json");
adresses = JsonConvert.DeserializeObject<List<adress>>(json_adress);

我收到以下错误:

"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[Mailer.adress]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly."`

也许有人可以帮助我更好地理解这个 json 的东西?

最佳答案

你几乎完成了,只是一个小错误。您提供的内容如下。请注意分隔处没有逗号。

{JSONSTUFF}
{JSONSTUFF}
{JSONSTUFF}

但是下面说你想把它转换成List<address>但它不是一个列表:(

JsonConvert.DeserializeObject<List<adress>>(json_adress);

所以实际上你需要提供的是一个地址列表,

[
{JSONSTUFF},
{JSONSTUFF},
{JSONSTUFF},
]

请不要忘记逗号:)

[{"name":"test1","email":["test1@test.de"],"imprint":"testimprint1 testimprint1","info2":"testinfo1"},{"name":"test2","email":["test2@test.de"],"imprint":"testimprint2 testimprint2","info2":"testinfo2"},{"name":"test3","email":["test3@test.de"],"imprint":"testimprint3 testimprint3","info2":"testinfo3"}]

关于c# - 将 JSON 转换为 C# 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45370875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com