简体   繁体   English

处理 JObject 与 JArray

[英]Dealing with a JObject vs a JArray

I have a method which receives this parameter:我有一个接收这个参数的方法:

List<QueueItem> signups

This is the class:这是课程:

public class QueueItem
{
  public string Everything{ get; set; } //all the fields in one string 
...
}

Everything has a string with all the fields from a Key Value pair object like this...一切都有一个字符串,其中包含来自键值对对象的所有字段,如下所示......

[{
  "Key": "Partner",
  "Value": "Place"
}, {
  "Key": "FIRST_NAME",
  "Value": "John"
}, {
  "Key": "last_name",
  "Value": "Smith"
}]

But this line...但是这条线...

var result = signups.Select(x => JsonConvert.DeserializeObject<JObject>(x.Everything));

Comes back with this error message:返回此错误消息:

"Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'" “无法将‘Newtonsoft.Json.Linq.JArray’类型的对象转换为‘Newtonsoft.Json.Linq.JObject’”

The solution I've seen is to not cast to JObject and leave it as JArray but that would require changing the rest of the method which checks JObject specific stuff like Properties() etc. I would love to be able to deal with the json as a JObject and keep everything else as is.我看到的解决方案是不强制转换为 JObject 并将其保留为 JArray,但这需要更改检查 JObject 特定内容(如 Properties() 等)的其余方法。我希望能够将 json 处理为一个 JObject 并保持其他一切不变。 Is there an efficient way to do that?有没有一种有效的方法来做到这一点?

Because later I constantly check JObject specific properties like this...因为后来我不断地检查 JObject 特定的属性,就像这样......

var Properties = result.Select(x => x.Properties()).ToArray();

what about deserializing straight to a List<KeyValuePair<string, string>> :直接反序列化为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 键值对文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM