【发布时间】:2019-09-18 14:26:36
【问题描述】:
我目前在 c# 中有一个List<Translations>,具有这种结构:
public class Translations
{
public string en { get; set; }
public string de { get; set; }
}
但我现在想将其转换为 Json Object ,因为我的函数通过 Ajax 调用此 Web 服务,需要完全具有以下结构的数据:
{
de: { //-> de stands for the stored value in translations class
'en_GB': en, //-> en stand for stored value in translations class
'de_DE': de // -> de same value as the key de
},
de: {
'en_GB': en,
'de_DE': de
},
de: {
'en_GB': en,
'de_DE': de
},
...
}
我该怎么做? 我已经尝试使用这个工具创建我需要的类:Json2CSharp,但这里的问题是我需要在我的对象中拥有每个对象的动态键名。使用这个工具,它会为每个对象创建一个静态对象。
解决方案 感谢 Riaz Raza 的帮助:
public static string getTranslations()
{
List<Translations> translations = Connector.TranslationList();
int count = translations.Count - 1;
var translationsObject = new Dictionary<string, object>();
for (int i = 0; i <= count; i++)
{
translationsObject.Add(
translations[i].de,
new Dictionary<string, object>() {
{ "en_GB", translations[i].en },
{ "de_DE", translations[i].de } }
);
}
return JsonConvert.SerializeObject(translationsObject);
}
【问题讨论】:
-
“完全符合以下结构” 你不能。这是无效的 JSON(重复键)
-
实际上
de:是动态的。每个de都有不同的值。所以没有重复的密钥。对不起,如果我没有解释清楚 -
你的问题很难理解。许多 JSON 序列化程序会将
IDictionary<TKey, TValue>转换为 JSON 中的动态命名值,但我不明白您想要的 JSON 如何映射到您的Translations类型定义。