简体   繁体   English

为什么Json.Encode没有正确编码从Json.Decode返回的数据?

[英]Why doesn't Json.Encode encode data returned from Json.Decode correctly?

When using the Json class from System.Web.Helpers and I run the following code, I expected it to produce a json string containing the same information as the original string, but strangely it only returns the string { "employees" : {} } and omits the array entirely and replaces it with an empty object? 当使用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" : {} }

When I look at the object returned from Json.Decode the array is decoded into a DynamicJsonArray. 当我查看从Json.Decode返回的对象时,数组被解码为DynamicJsonArray。 If I create a .NET object with arrays/lists/dictionaries it seems to encode them perfectly so the problem seems to be related to DynamicJsonArray. 如果我使用数组/列表/字典创建一个.NET对象,它似乎完美地编码它们,所以问题似乎与DynamicJsonArray有关。

If I encode/decode a complex json string without arrays it seems to be working fine: 如果我编码/解码没有数组的复杂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"
          }
     }
}
*/

I have looked at the documentation on msdn but couldn't find any reasons why this shouldn't work. 我查看了msdn上的文档,但找不到任何原因,为什么这不起作用。 Could it be a bug or is it by design? 它可能是一个错误还是设计?

Update 更新

If I have a json string that's an array at the root node, it encodes/decodes correctly so I really start to suspect that this is a bug (or at least it's very inconsistent): 如果我有一个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"
    }
]
*/

Update 2 更新2

I decided to open an issue with Microsoft after all. 毕竟我决定向微软提出一个问题。 Let's see what they have to say: http://connect.microsoft.com/VisualStudio/feedback/details/779119/data-from-json-decode-is-not-encoded-correctly-when-encoding-with-json-encode 让我们看看他们要说些什么: http//connect.microsoft.com/VisualStudio/feedback/details/779119/data-from-json-decode-is-not-encoded-correctly-when-encoding-with-json-编码

I'm experiencing this bug too, luckily the library is now open source so we can fix the bug ourselves: https://aspnetwebstack.codeplex.com/SourceControl/latest 我也遇到了这个错误,幸运的是这个库现在是开源的,所以我们可以自己解决这个问题: https//aspnetwebstack.codeplex.com/SourceControl/latest

The fix is in System.Web.Helpers/DynamicJavaScriptConverter.cs 修复程序位于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;
}

I've filed a bug with the suggested fix on the codeplex site: https://aspnetwebstack.codeplex.com/workitem/1085 我在codeplex网站上提交了一个建议修复程序的错误: https ://aspnetwebstack.codeplex.com/workitem/1085

I think you should be using Json.NET instead. 我认为你应该使用Json.NET。 See: Json.NET on Codeplex 请参阅: Codeplex上的Json.NET

Have you thought about creating and using classes, which you then can serialize / deserialize them? 您是否考虑过创建和使用类,然后可以对它们进行序列化/反序列化?

JavaScriptSerializer serializer = new JavaScriptSerializer();
// to JSON
string json = serializer.Serialize(EmployeeList);
// from JSON
EmployeeList employeeList = serializer.Deserialize<EmployeeList>(json);

I almost always serialize / deserialize, because I need the data as an object for use during execution. 我几乎总是序列化/反序列化,因为我需要将数据作为在执行期间使用的对象。 But I guess that depends on your case. 但我想这取决于你的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何防止Json.Encode / Decode在C#中将字符转换为中文字母? - How to keep Json.Encode/Decode from converting characters into chinese letters in C#? 如何从Json.Encode(Model)过滤JSON返回 - How to filter a JSON return from Json.Encode(Model) 为什么Json.Decode不能在C#中处理数组? - Why can't Json.Decode handle arrays in C#? 为什么在Json.decode或默认模型绑定中无法从int到intBox进行隐式转换? - Why isn't an implicit conversion from int to intBox working in Json.decode or default modelbinding? JSON.ENCODE将带有空间的变量拆分为多个变量 - JSON.ENCODE is splitting variable with space into multiple variables 使用@Json.Encode时隐藏模型中的字段 - Hide field in model when using @Json.Encode Json.Encode()是否使用JavaScriptSerializer类进行序列化 - Does Json.Encode() use JavaScriptSerializer Class to serialize Json.Encode对象,其数组字符串为“ []”而不是null - Json.Encode object with array string to “[ ]” instead of null Json.net在Web API中使用,但在Razor模板中调用Json.Encode时却没有 - Json.net used in Web API but not when calling Json.Encode in Razor Template 使用 Newtonsoft JSON 指定要编码和解码的属性和字段 - Specify properties and field to encode and decode with Newtonsoft JSON
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM