.net WCF - 如何在 JSON 中序列化和反序列化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15392600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WCF - How to serialize and deserialize in JSON?
提问by Pavan Welihinda
I have written few classes (Data contracts and Service contracts) in WCF and i'm trying to serialize and deserialize in JSON. If i need the following JSON structure, how would i create the DataContract(s):
我在 WCF 中编写了几个类(数据合同和服务合同),我正在尝试在 JSON 中进行序列化和反序列化。如果我需要以下 JSON 结构,我将如何创建 DataContract(s):
{
"response": {
"locations": {
"location": [
{
"id": "12",
"name": "Hello",
"statusid": "78"
},
{
"id": "5",
"name": "Ann",
"statusid": "8"
}
]
},
"error": "404 error"
}
}
The structure above is pretty straight forward and under locations there can be several location details as mentioned above. So i need to get an array/list to "locations" data members as mentioned below. At the moment i have the following DataContract only:
上面的结构非常简单,在位置下面可以有几个如上所述的位置详细信息。所以我需要获取一个数组/列表来“位置”数据成员,如下所述。目前我只有以下 DataContract:
[DataContract]
public class Response
{
[DataMember]
public string locations { get; set; }
[DataMember]
public string error{ get; set; }
}
Please let me know how i can resolve this?
请让我知道我该如何解决这个问题?
回答by Mike Guthrie
The full objects you are looking for should be structured as:
您正在寻找的完整对象的结构应为:
[DataContract(Name="response")]
public class Response
{
[DataMember(Name = "locations")]
public IEnumerable<Location> Locations { get; set; }
[DataMember(Name = "error")]
public string Error { get; set; }
}
[DataContract(Name = "location")]
public class Location
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "statusid")]
public string StatusId { get; set; }
}
You need to setup the object hierarchy, as indicated by the {and }, as well as the IEnumerable / array properties, as indicated by the [and ]from your desired JSON output.
你需要设置对象分层结构,如由所指示的{和},以及了IEnumerable /阵列的属性,由所指示的[并]从你的期望的JSON输出。
The site can be confusing, as there are no simple examples, but please review Introducing JSONfor a basic understanding of the syntax. Another good site I came along, with just some simple examples, was JSON and XML Serialization in ASP.NET Web API.
该站点可能会令人困惑,因为没有简单的示例,但请查看JSON 简介以对语法有基本的了解。我遇到的另一个很好的站点,只是一些简单的例子,是ASP.NET Web API 中的 JSON 和 XML 序列化。
Thanks to some guidance by vittore, I noticed that to build the exact match to your JSON output, you will need objects like:
感谢 vittore 的一些指导,我注意到要构建与您的 JSON 输出完全匹配的对象,您将需要以下对象:
[DataContract]
public class ResponseParent
{
[DataMember(Name = "response")]
public Response ResponseInstance { get; set; }
}
[DataContract]
public class Response
{
[DataMember(Name = "locations")]
public LocationCollectionIntermediate Locations { get; set; }
[DataMember(Name = "error")]
public string Error { get; set; }
}
[DataContract]
public class LocationCollectionIntermediate
{
[DataMember(Name = "location")]
public IEnumerable<Location> Locations { get; set; }
}
[DataContract]
public class Location
{
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "statusid")]
public string StatusId { get; set; }
}
I've added these into a second code block here, because such a structure seems needlessly complicated. However, if you are in a position where you can change the expected output of your JSON, I'd go with the first block, with the additional change of making the two Idcolumns into inttypes.
我已经将这些添加到这里的第二个代码块中,因为这样的结构似乎不必要地复杂。但是,如果您处于可以更改 JSON 预期输出的位置,我会使用第一个块,并进行将两Id列转换为int类型的额外更改。
These types were created to support a service similar to as setup at WCF Service to return JSON, and tested using the following code:
创建这些类型是为了支持类似于在WCF 服务中设置的服务以返回 JSON,并使用以下代码进行测试:
string json;
using (var ms = new MemoryStream())
{
var ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(ResponseParent));
ser.WriteObject(ms, r);
json = System.Text.Encoding.UTF8.GetString(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
}
Details on DataContractJsonSerializer
DataContractJsonSerializer 的详细信息
Note also that if you have the option to setup a RESTful web service, then you can follow the guidelines of How to create a JSON WCF RESTful Service in 60 seconds.
另请注意,如果您可以选择设置 RESTful Web 服务,那么您可以遵循如何在 60 秒内创建 JSON WCF RESTful 服务的指南。
回答by lcryder
Visit http://json.codeplex.com/. Use
JsonConvert.SerializeObject()
to turn your object into a JSON string. Use
将您的对象转换为 JSON 字符串。用
JsonConvert.PopulateObject
to turn JSON string into an object.
将 JSON 字符串转换为对象。
回答by Sándor Mátyás Márton
Once you have the exact, attributed structure, you can also use the JavaScriptSerializerclass from System.Web.Script.Serialization(since .NET 3.5)
一旦你有了确切的属性结构,你还可以使用JavaScriptSerializer类System.Web.Script.Serialization(自 .NET 3.5 起)
Something like this will work:
像这样的事情会起作用:
string jsonString;
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response responseObject = serializer.Deserialize<Response>(jsonString);
Even simpler than using DataContractSerializer, though I'm not entirely sure about its caveats. I have used it several times without any problems.
甚至比 using 更简单DataContractSerializer,尽管我不完全确定它的注意事项。我已经多次使用它没有任何问题。
You can also add custom JavaScriptConverters, which makes it possible to implement a nicer way of dynamic JSON parsingwith relative ease.
您还可以添加自定义JavaScriptConverter,这使得可以相对轻松地实现更好的动态 JSON 解析方式。
Dynamic parsing is also very simple this way:
这样动态解析也很简单:
string jsonString;
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic responseObject = serializer.Deserialize<object>(jsonString);
responseObject["locations"] = ...

