【问题标题】:JsonConvert.DeserializeAnonymousType definition syntax issueJsonConvert.DeserializeAnonymousType 定义语法问题
【发布时间】:2019-08-09 22:33:29
【问题描述】:

我有以下代码:

var definition = new { result = "", accountinformation = new[] { "" ,  "" , "" } };

var accountInformationResult = JsonConvert.DeserializeAnonymousType(responseBody, definition);

帐户信息结构作为数组从端点返回,每个元素是另一个包含 3 个字符串的数组。所以嵌入数组不是键值对格式。使用上面的定义 accountinformation 返回 null。这个结构的语法应该是什么?

作为参考,这是 php 端点中发生的事情。

$account_information[] = array( $billing_company, $customer_account_number, $customer_account_manager );

第一行是一个循环。因此是多维数组。

echo json_encode(array('result'=>$result, 'account_information'=>$account_information));

我知道我可以使用动态,但为什么要付出额外的努力?

【问题讨论】:

  • 如果您将名称从 accountinformation 更改为 accountInformation(大写“I”),您能看到会发生什么吗?
  • 我仍然得到大写 I 的空结果。我确实尝试过 new[][] { "", "", "" } 但那甚至无法编译!
  • 还有 account_information?
  • 不喜欢下划线。我正在更改其他系统中的代码以删除下划线。在更改代码以便两个系统都使用帐户信息之后,我现在得到了另一个错误。 JsonReaderException:解析值时遇到意外字符:[。路径“accountinformation”,第 1 行,位置 38。我假设这是 new 之后的方括号。
  • 查看我的答案,让它在控制台应用程序中工作。

标签: c# arrays definition jsonconvert


【解决方案1】:

我假设你的 json 看起来像这样:

{
  "result": "the result",
  "account_information": [
    ["company1", "account_number1", "account_manager1"],
    ["company2", "account_number2", "account_manager2"]
  ]
}

在这种情况下,您应该能够使用以下定义进行反序列化(注意 account_information 中的下划线:

var definition = new { result = "", account_information = new List<string[]>() };

在 json 中,您可以在数据模型更改时随意添加额外的属性。因此,如果您定义的数据模型不包含这些属性之一,则该属性将被简单地忽略。在您的情况下,该定义没有名为 account_information 的属性(完全正确),因此在反序列化时会忽略这部分 json。

编辑: 如果反正要匿名,也可以考虑解析成JObject

var obj = JObject.Parse(responseBody);
string firstCompany = obj["account_information"][0][0];
string secondCompany = obj["account_information"][1][0];

【讨论】:

  • 包含列表语法的答案返回 null。在上面的 cmets 中,我详细介绍了对我有用的方法。即: var definition = new { result = "", accountinformation = new[,] { { "", "", "" } } }
  • 好的,那么 json 看起来不像我在答案中显示的那样。
  • 不完全是,account_information 将包含 [["string", "string","string"],["string", "string", "string"] ... ] 等多行有数据。
  • 好吧,为了完整起见更新了我的答案。
  • 是的,您的回答确实有效。我正在使用你的版本。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2011-05-09
  • 2018-10-04
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多