【问题标题】:Dynamic Json string access a value动态 Json 字符串访问一个值
【发布时间】:2021-01-08 00:10:19
【问题描述】:

    {
  "ErrorNumber": 10,
  "Type": "ValidationException",
  "Message": "A validation exception occurred",
  "Elements": [
    {
      "ContactID": "00000000-0000-0000-0000-000000000000",
      "Name": "Test AB",
      "EmailAddress": "abc@gmail.com",
      "Addresses": [
        {
          "AddressType": "POBOX",
          "ValidationErrors": []
        }
      ],
      "Phones": [],
      "ContactGroups": [],
      "IsCustomer": true,
      "ContactPersons": [],
      "HasValidationErrors": true,
      "ValidationErrors": [
        {
          "Message": "The contact name Test AB is already assigned to another contact. The contact name must be unique across all active contacts."
        }
      ]
    }
  ]
}

试图反序列化对象。

var x = ((Xero.NetStandard.OAuth2.Client.ApiException)ex.InnerException).ErrorContent;
                dynamic parsedObject = JsonConvert.DeserializeObject(x);

我有一个来自 Xero API 异常的动态 Json 字符串。如何访问值“ValidationErrors”和消息?

【问题讨论】:

  • 你能提供你正在使用的编程语言吗?到目前为止你尝试了什么?
  • C# 代码。动态解析对象 = JsonConvert.DeserializeObject(x);但我似乎无法访问数组内的数组
  • 这能回答你的问题吗? how to access JSON object in C#
  • 我试过了,但是不行
  • var result = JObject.Parse(error)["Elements"][0]["ValidationErrors"][0] 但是你的问题不是很清楚......你可以正确地反序列化它,虽然谁知道他们有什么时髦的格式。

标签: c# json json.net


【解决方案1】:

使用json.net,您可以使用字符串索引器浏览图表

var errors = JObject.Parse(json)["Elements"][0]["ValidationErrors"];

foreach (var error in errors)
   Console.WriteLine(error["Message"]);

输出

The contact name Test AB is already assigned to another contact. The contact name must be unique across all active contacts.

【讨论】:

  • 抛出异常“无法访问 Newtonsoft.Json.Linq.JProperty 上的子值。”
  • @Shereen 我粘贴了您的 exact json,它对我有用 dotnetfiddle.net/mvpPB7
猜你喜欢
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
相关资源
最近更新 更多