DataContractJsonSerializer

DataContractJsonSerializer

本文介绍了有什么方法可以让 DataContractJsonSerializer 正确序列化字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DataContractJsonSerializer 无法正确序列化字典.

The DataContractJsonSerializer is not able to serialize Dictionaries properly.

JavaScriptSerializer 将字典序列化为 {"abc":"xyz","def":42}例如,DataContractJsonSerializer 给 [{"Key":"abc","Value":"xyz"},{"Key":"def","Value":42}] 代替.

Whereas JavaScriptSerializer serializes Dictionaries as {"abc":"xyz","def":42}for example,the DataContractJsonSerializer gives [{"Key":"abc","Value":"xyz"},{"Key":"def","Value":42}] instead.

这确实有问题,我想知道如何在 WCF 服务中正确序列化 Dictionary 对象.我正在寻找一种需要最少努力的解决方案.

This is really problematic and I want to know how can I serialize Dictionary objects correctly in my WCF service. I am looking for a solution that would require least amount of effort.

参考:http://msdn.microsoft.com/en-us/图书馆/bb412170.aspx

这是我最终用来在 WCF 中正确序列化字典的解决方法:http://social.msdn.microsoft.com/forums/en-US/wcf/thread/765f1569-0422-4471-8ec2-1d03b2026771

This is the workaround I finally used to serilize dictionaries properly in WCF: http://social.msdn.microsoft.com/forums/en-US/wcf/thread/765f1569-0422-4471-8ec2-1d03b2026771

推荐答案

使用 DataContractJsonSerializerSettings(从 .NET 4.5 开始可用)可以为您做到这一点:

Using DataContractJsonSerializerSettings (available since .NET 4.5) can do this for you:

var serializer = new DataContractJsonSerializer(typeOfObj, new DataContractJsonSerializerSettings()
{
    UseSimpleDictionaryFormat = true
});

这篇关于有什么方法可以让 DataContractJsonSerializer 正确序列化字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 08:43