JsonConvert.DeserializeAnonymousType 定义语法问题
JsonConvert.DeserializeAnonymousType definition syntax issue
我有以下代码:
var definition = new { result = "", accountinformation = new[] { "" , "" , "" } };
var accountInformationResult = JsonConvert.DeserializeAnonymousType(responseBody, definition);
帐户信息结构作为一个数组从端点返回,每个元素都是另一个包含 3 个字符串的数组。所以嵌入式数组不是键值对格式。用上面定义的accountinformation returns null。这个结构的语法应该是什么?
作为参考,这是 php 端点中发生的事情。
$account_information[] = array( $billing_company, $customer_account_number, $customer_account_manager );
第一行在循环中。因此多维数组。
echo json_encode(array('result'=>$result, 'account_information'=>$account_information));
我知道我可以使用动态,但为什么要付出额外的努力?
我假设您的 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];
我有以下代码:
var definition = new { result = "", accountinformation = new[] { "" , "" , "" } };
var accountInformationResult = JsonConvert.DeserializeAnonymousType(responseBody, definition);
帐户信息结构作为一个数组从端点返回,每个元素都是另一个包含 3 个字符串的数组。所以嵌入式数组不是键值对格式。用上面定义的accountinformation returns null。这个结构的语法应该是什么?
作为参考,这是 php 端点中发生的事情。
$account_information[] = array( $billing_company, $customer_account_number, $customer_account_manager );
第一行在循环中。因此多维数组。
echo json_encode(array('result'=>$result, 'account_information'=>$account_information));
我知道我可以使用动态,但为什么要付出额外的努力?
我假设您的 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];