【问题标题】:How to Parse this Json String using JObject如何使用 JObject 解析这个 Json 字符串
【发布时间】:2015-12-19 20:51:28
【问题描述】:
[
  ["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" } ]
  ]
]

使用 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)

但是当我将上面的字符串复制到在线 Json 查看器中时,它们似乎都解析得很好。

【问题讨论】:

    标签: json parsing json.net


    【解决方案1】:

    您的 JSON 不代表对象;它是一个数组(数组)。因此,您不能使用JObject.Parse()。请改用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())));
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多