gpt4 book ai didi

c# - 为什么 Json.Encode 不能正确编码从 Json.Decode 返回的数据?

转载 作者:可可西里 更新时间:2023-11-01 08:27:33 25 4
gpt4 key购买 nike

当使用 System.Web.Helpers 中的 Json 类并运行以下代码时,我希望它生成一个包含与原始字符串相同信息的 json 字符串,但奇怪的是它只返回字符串 { "employees": {} } 并完全省略数组并将其替换为空对象?

string jsonData = "{ \"employees\": [ { \"firstName\":\"John\" , \"lastName\":\"Doe\" }, { \"firstName\":\"Anna\" , \"lastName\":\"Smith\" }, { \"firstName\":\"Peter\" , \"lastName\":\"Jones\" } ] }";
var json = Json.Decode(jsonData);
string result = Json.Encode(json);
// result is: { "employees" : {} }

当我查看从 Json.Decode 返回的对象时,数组被解码为 DynamicJsonArray。如果我用数组/列表/字典创建一个 .NET 对象,它似乎对它们进行了完美编码,因此问题似乎与 DynamicJsonArray 有关。

如果我编码/解码一个没有数组的复杂 json 字符串,它似乎工作正常:

string jsonData = "{ \"firstName\": \"John\", \"lastName\": \"Doe\", \"family\": { \"mother\": { \"firstName\": \"Anna\", \"lastName\": \"Smith\" }, \"father\": { \"firstName\": \"Peter\", \"lastName\": \"Jones\" }  }  }";
var json = Json.Decode(jsonData);
string result = Json.Encode(json);
/* result is (formatted for readability):
{
"firstName" : "John",
"lastName" : "Doe",
"family" : {
"mother" : {
"firstName" : "Anna",
"lastName":"Smith"
},
"father" : {
"firstName" : "Peter",
"lastName" : "Jones"
}
}
}
*/

我已经查看了 msdn 上的文档,但找不到任何不可行的原因。这可能是错误还是设计使然?

更新

如果我在根节点有一个 json 字符串,它是一个数组,它会正确编码/解码,所以我真的开始怀疑这是一个错误(或者至少它非常不一致):

string jsonData = "[ { \"firstName\":\"John\" , \"lastName\":\"Doe\" }, { \"firstName\":\"Anna\" , \"lastName\":\"Smith\" }, { \"firstName\":\"Peter\" , \"lastName\":\"Jones\" } ]";
var json = Json.Decode(jsonData);
string result = Json.Encode(json);
/* result is (formatted for readability):
[
{
"firstName" : "John",
"lastName" : "Doe"
},
{
"firstName" : "Anna",
"lastName" : "Smith"
},
{
"firstName" : "Peter",
"lastName" : "Jones"
}
]
*/

更新2

毕竟我决定向 Microsoft 提出问题。让我们看看他们要说什么: http://connect.microsoft.com/VisualStudio/feedback/details/779119/data-from-json-decode-is-not-encoded-correctly-when-encoding-with-json-encode

最佳答案

我也遇到了这个错误,幸运的是这个库现在是开源的,所以我们可以自己修复这个错误: https://aspnetwebstack.codeplex.com/SourceControl/latest

修复在 System.Web.Helpers/DynamicJavaScriptConverter.cs 中

// Get the value for each member in the dynamic object
foreach (string memberName in memberNames)
{
//replace this line
//values[memberName] = DynamicHelper.GetMemberValue(obj, memberName);

//with this code
var value = DynamicHelper.GetMemberValue(obj, memberName);
if (value is DynamicJsonArray)
value = (object[])(DynamicJsonArray)value;
values[memberName] = value;
}

我已经在 codeplex 站点上提交了一个带有建议修复的错误: https://aspnetwebstack.codeplex.com/workitem/1085

关于c# - 为什么 Json.Encode 不能正确编码从 Json.Decode 返回的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14850170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com