简体   繁体   English

如何使用JObject解析此Json字符串

[英]How to Parse this Json String using JObject

[
  ["Sender", "service@mydomain.com"], 
  ["Date", "Sat, 19 Dec 201520:41:31 +0000"], 
  ["X-Mailgun-Sid", "WyI0ZjRjNyIsICJyYWplZXZrbXh4eddHh4eDMzMzMzQHlhaG9vLmNvbSIsICJjNGExZiJd"],
  ["Received", "by luna.mailgun.net with HTTP; Sat, 19 Dec 2015 20:41:31+0000"], 
  ["Message-Id", "<201512192024131.73374.12565@mydomain.com>"], 
  ["Reply-To", "junky01@hotmail.com"], 
  ["X-Mailgun-Skip-Verification", "false"], 
  ["To", "John Myers <testxxxxxx33333@yahoo.com>"], ["From", "\"Inc.\" <service@mydomain.com>"], 
  ["Subject", "Test subject"],
  ["Mime-Version", "1.0"], 
  ["Content-Type", 
      ["multipart/mixed", { "boundary": "e43d638b70f04a40889d14f4c8422953" } ]
  ]
]

When using JObject (VB.net), JObject.parse throws this error: 使用JObject(VB.net)时,JObject.parse引发此错误:

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 2, position 2.---- at Newtonsoft.Json.Linq.JObject.Load(JsonReader reader) at Newtonsoft.Json.Linq.JObject.Parse(String json)

But when I copy the above string into online Json viewers, they all seem to be parsing it fine. 但是,当我将上述字符串复制到在线Json查看器中时,他们似乎都在解析它。

Your JSON does not represent an object; 您的JSON不代表对象; it is an array (of arrays). 它是一个(数组)数组。 Therefore, you cannot use JObject.Parse() . 因此,您不能使用JObject.Parse() Instead, use JArray.Parse() , which can handle arrays, or use JToken.Parse() , which can handle either arrays or objects. 相反,使用JArray.Parse()它可以处理阵列,或使用JToken.Parse()它可以处理任一阵列或对象。

string json = @"
[
  [""Sender"", ""service@mydomain.com""], 
  [""Date"", ""Sat, 19 Dec 201520:41:31 +0000""], 
  [""X-Mailgun-Sid"", ""WyI0ZjRjNyIsICJyYWplZXZrbXh4eddHh4eDMzMzMzQHlhaG9vLmNvbSIsICJjNGExZiJd""],
  [""Received"", ""by luna.mailgun.net with HTTP; Sat, 19 Dec 2015 20:41:31+0000""], 
  [""Message-Id"", ""<201512192024131.73374.12565@mydomain.com>""], 
  [""Reply-To"", ""junky01@hotmail.com""], 
  [""X-Mailgun-Skip-Verification"", ""false""], 
  [""To"", ""John Myers <testxxxxxx33333@yahoo.com>""], 
  [""From"", ""\""Inc.\"" <service@mydomain.com>""], 
  [""Subject"", ""Test subject""],
  [""Mime-Version"", ""1.0""], 
  [""Content-Type"", 
      [""multipart/mixed"", { ""boundary"": ""e43d638b70f04a40889d14f4c8422953"" } ]
  ]
]";

JArray rows = JArray.Parse(json);
foreach (JArray row in rows)
{
    Console.WriteLine(string.Join(": ", row.Select(r => r.ToString())));
}

Fiddle: https://dotnetfiddle.net/VRs47S 小提琴: https : //dotnetfiddle.net/VRs47S

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

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