C# - JObject.Parse - 无效的 JSON

标签 c# json wcf json.net

我正在使用返回 JSON 的 API。

我有一个调用 api 的方法,并为所需的节点解析 JSON 响应。

到目前为止,一切正常,除了最新的 JSON 响应格式不正确。

其他回复如:

{
   "Keyword":"\"marhope\"",
   "TermKey":null,
   "Customers":[
      {
         "Memberships":[ ],
         "CompanyId":0,
         "ObjectId":112974,
         "ObjectType":"Customer",

      }
   ]
}

我使用 JObject.Parse 按名称取回适当的节点。

最新的 JSON 响应返回为:

{
   [
      {
         "AnimalId":9079117,
         "SpeciesCode":"XX",
      }
   ]
}   

如您所见,没有“名称”,JSON 略有无效。

我怎样才能解析这个。对于第一个示例,我使用了下面的代码,但现在 JSON 没有“名称”,我不知道如何处理这个,有什么想法吗?

JObject results = JObject.Parse(csr.SearchCustomer(1, 1, 870, term));
foreach (var resp in results["Customers"])
{
    string obj = (string)resp["CompanyId"];
}

最佳答案

Jon Skeet 是正确的,第二个 JSON 无效:您不能在没有属性名称的对象中直接使用数组。最好的做法是让 API 开发人员修复 JSON。但是,如果您只是在寻找一种快速而肮脏的解决方法,您可以从无效的 JSON 中删除第一个和最后一个大括号,然后使用 JArray.Parse 将其解析为数组。 .

string json = @"{
   [
      {
         ""AnimalId"":9079117,
         ""SpeciesCode"":""XX"",
      }
   ]
}";

json = json.Substring(1, json.Length - 2);
JArray array = JArray.Parse(json);
foreach (JObject item in array.Children<JObject>())
{
    Console.WriteLine("AnimalId: " + item["AnimalId"]);
    Console.WriteLine("SpeciesCode: " + item["SpeciesCode"]);
}

关于C# - JObject.Parse - 无效的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29145913/

相关文章:

c# - 在 .NET 中使用 RabbitMQ 发布/订阅示例

c# - GDI+ 中发生一般性错误。 (仅当我在服务器上尝试时)

c# - 使用 Graph API 在 Azure Active Directory (B2C) 中使用 http post 请求创建新用户

java - 错误检查对象为空

c# - Silverlight 客户端 HTTP 堆栈与浏览器 HTTP 堆栈

c# - 将数据从SSIS错误日志表加载到SQL Server表时出错

javascript - Ajax - 处理大量数据的最佳技术

javascript - PHP 无法读取 jQuery.ajax POST 中发送的数据

visual-studio-2008 - 为什么我的服务引用只生成异步方法?

c# - 在 Visual Studio 2013 中运行单元测试时运行其他项目