c# - 处理 JObject 与 JArray

标签 c# json

我有一个接收这个参数的方法:

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}");
}

KeyValuePair documentation

关于c# - 处理 JObject 与 JArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54563367/

相关文章:

c# - 对于数据表 C# 中的字符串字段,列的 MaxLength 似乎始终为 -1

c# - 使用 jQuery .load() 加载用户控件

c# - 此 Icomparer 中导致空引用的不一致在哪里?

javascript - 在javascript中使用php数组填充 'select' ajax

php - 如何使用 json 对象数组生成有效的 json 输出

java - Jackson readTree() 忽略 null 和空值

c# - 了解 C# 中委托(delegate)的要点

c# - ServerManager 如何找到给定站点的状态

android - 如何在 JSON 数组 Android 中解析 JSON 数组

python - 为什么使用 pandas.read_json 读取字符串整数不正确?