解析字段名称不一致的 JSON 字符串
Parse JSON string with inconsistent field names
我在反序列化以下 JSON 结构时遇到问题。每个节点都包含一个 ID 和带有值的多语言代码。语言属性的数量不一致。但我需要这些值作为具有语言字段和值字段的对象列表。
[{
"id":"w_312457",
"eng":"deep-fat frying",
"ger":"Frittieren"
},
{
"id":"w_312458",
"fre":"frying",
"ger":"braten (in Öl)"
},
{
"id":"w_312477",
"ger":"perfekt gewürzte und abgestimmte Soße "
}]
我尝试使用 JsonPropertyName
属性并获得了 ID 值。但是对于 lang 节点,我不知道我可以指定什么名称。以下是我的 CLR 对象,
public class Word
{
public string Id { get; set; } // This is working
// What can I specify here. I need a list of objects each with a lang code and value.
}
方法一:
一种方法是简单地添加所有值并检查它们是否存在。例如,这是包含所有语言值的 class:
public class Word
{
public string id { get; set; }
public string eng { get; set; }
public string ger { get; set; }
public string fre { get; set; }
}
你得到的列表如下:
var words = JsonConvert.DeserializeObject<List<Word>>(json);
当然这是假设只有 3 种语言并且不会添加更多语言(这永远不会发生!)
方法二:
如 this 线程所示,您可以像这样反序列化为字典对象列表:
var words = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);
您可以像这样访问所有键和值:
foreach (var word in words)
{
foreach (var key in word.Keys)
{
Console.WriteLine($"value for the key {key} is {word[key]}");
}
}
这将产生以下结果:
value for the key id is w_312457
value for the key eng is deep-fat frying
value for the key ger is Frittieren
value for the key id is w_312458
value for the key fre is frying
value for the key ger is braten (in Öl)
value for the key id is w_312477
value for the key ger is perfekt gewürzte und abgestimmte Soße
我在反序列化以下 JSON 结构时遇到问题。每个节点都包含一个 ID 和带有值的多语言代码。语言属性的数量不一致。但我需要这些值作为具有语言字段和值字段的对象列表。
[{
"id":"w_312457",
"eng":"deep-fat frying",
"ger":"Frittieren"
},
{
"id":"w_312458",
"fre":"frying",
"ger":"braten (in Öl)"
},
{
"id":"w_312477",
"ger":"perfekt gewürzte und abgestimmte Soße "
}]
我尝试使用 JsonPropertyName
属性并获得了 ID 值。但是对于 lang 节点,我不知道我可以指定什么名称。以下是我的 CLR 对象,
public class Word
{
public string Id { get; set; } // This is working
// What can I specify here. I need a list of objects each with a lang code and value.
}
方法一:
一种方法是简单地添加所有值并检查它们是否存在。例如,这是包含所有语言值的 class:
public class Word
{
public string id { get; set; }
public string eng { get; set; }
public string ger { get; set; }
public string fre { get; set; }
}
你得到的列表如下:
var words = JsonConvert.DeserializeObject<List<Word>>(json);
当然这是假设只有 3 种语言并且不会添加更多语言(这永远不会发生!)
方法二:
如 this 线程所示,您可以像这样反序列化为字典对象列表:
var words = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(json);
您可以像这样访问所有键和值:
foreach (var word in words)
{
foreach (var key in word.Keys)
{
Console.WriteLine($"value for the key {key} is {word[key]}");
}
}
这将产生以下结果:
value for the key id is w_312457
value for the key eng is deep-fat frying
value for the key ger is Frittieren
value for the key id is w_312458
value for the key fre is frying
value for the key ger is braten (in Öl)
value for the key id is w_312477
value for the key ger is perfekt gewürzte und abgestimmte Soße