gpt4 book ai didi

c# - 如何转换 Json key :value into value:value in C#?

转载 作者:行者123 更新时间:2023-12-04 10:04:59 32 4
gpt4 key购买 nike

我正在读取 C# 中的资源文件并将其转换为 JSON 字符串格式。现在我想将该 JSON 字符串的值转换为键。

例子,

[
{
"key": "CreateAccount",
"text": "Create Account"
},
{
"key": "EmailAddress",
"text": "Email Address"
}
]

所以我只想将上面的json字符串变成“Key:text”,如下所示,
[
{
"CreateAccount": "Create Account"
},
{
"EmailAddress": "Email Address"
}
]

我的C#,
var obj = new
{
Lang=XElement.Parse(_FileDataAsText)
.Elements("data")
.Select(el => new
{
key= el.Attribute("name").Value,
text = el.Element("value").Value
}.ToList()
};

string json = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);

最佳答案

创建一个类来表示内部 JSON 对象:

public class RootObject
{
public string Key { get; set; }
public string Text { get; set; }
}

然后将 JSON 数组反序列化为 List<RootObject>使用 Json.NET , 投影对象 keytextDictionary<string, string> 中的键值对使用 Enumerable.Select ,然后将结果序列化为 List<Dictionary<string, string>> .
using Newtonsoft.Json;

...

var json = @"[{""key"": ""CreateAccount"",""text"": ""Create Account""},{""key"": ""EmailAddress"",""text"": ""Email Address""}]";

var deserializedJson = JsonConvert
.DeserializeObject<List<RootObject>>(json);

var result = deserializedJson
.Select(obj => new Dictionary<string, string> {
{ obj.Key, obj.Text }
})
.ToList();

var serializedJson = JsonConvert.SerializeObject(result, Formatting.Indented);

Console.WriteLine(serializedJson);

输出:
[
{
"CreateAccount": "Create Account"
},
{
"EmailAddress": "Email Address"
}
]

关于c# - 如何转换 Json key :value into value:value in C#?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61631754/

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