我有一个接收这个参数的方法:
List<QueueItem> signups
这是类:
public class QueueItem
{
public string Everything{ get; set; } //all the fields in one string
...
}
一切都有一个字符串,其中包含键值对对象中的所有字段,如下所示...
[{
"Key": "Partner",
"Value": "Place"
}, {
"Key": "FIRST_NAME",
"Value": "John"
}, {
"Key": "last_name",
"Value": "Smith"
}]
但是这一行...
var result = signups.Select(x => JsonConvert.DeserializeObject<JObject>(x.Everything));
返回此错误消息:
“无法将‘Newtonsoft.Json.Linq.JArray’类型的对象转换为‘Newtonsoft.Json.Linq.JObject’类型”
我看到的解决方案是不转换为 JObject 并将其保留为 JArray 但这将需要更改检查 JObject 特定内容(如 Properties() 等)的方法的其余部分。我希望能够处理json 作为 JObject 并保持其他一切不变。有没有一种有效的方法来做到这一点?
因为后来我经常像这样检查 JObject 特定的属性...
var Properties = result.Select(x => x.Properties()).ToArray();
最佳答案
直接反序列化为List<KeyValuePair<string, string>>
怎么样? :
var pairs = JsonConvert.DeserializeObject<List<KeyValuePair<string, string>>>(x.Everything);
foreach(var kvp in pairs)
{
Console.WriteLine($"Key: {kvp.Key}");
Console.WriteLine($"Value: {kvp.Value}");
}
关于c# - 处理 JObject 与 JArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54563367/