如何使用带有json动态成员的WCF DataContract [英] How to have a WCF DataContract with a json dynamic member
问题描述
在我正在从事的项目中,我们要求有一个DataContract,其中可以包含一些未定义的JSON.
at the project I am working on, we have a requirement to have a DataContract that can contain some undefined JSON.
DataMember是仅对客户端有意义的一些JSON.我们希望允许客户端向我们发送我们不知道的json.
The DataMember is some JSON that makes sense to the client only. We want to allow the client to send us json we do not know about.
示例:
public class Contract
{
[DataMember]
public int clientId;
[DataMember]
public string json;
}
很明显,具有这样的约定将要求客户端像这样对json进行转义:
Obviously, having a contract defined like that would require the client to escape the json like this:
{
"clientId":1,
"json": "{\"test\":\"json\"}"
}
显然,这不是我们所需要的.客户端应发送给我们的json应该如下所示:
Obviously, this is not what we need. The json the client should sent us should look like this:
{
"clientId":1,
"json": {"test":"json"}
}
我们调查了可能的解决方案:
Possible solutions we investigated:
- 使用Stream作为请求正文的合同参数.可以,但是可以代替我们使用框架.
- 将"json"定义为DynamicObject.不起作用.无法正确编写属性.
- 使用Newtonsoft库,在WCF端点中更改默认协定序列化程序,以将所有输入序列化到JObject.我们还会根据请求处理序列化,这会在我们的应用程序中引起问题.我们宁愿避免这种方式.
有人可以解决这个问题吗?
Does anyone have a possible solution to this problem?
编辑
该服务提供其余的json资源.它使用webHttpBinding定义单个端点. 该操作的定义如下(为简单起见,将其简化):
The service offers rest json resources. It defines a single endpoint with webHttpBinding. The operation is defined like this (stripped down for simplicity):
[WebInvoke(Method = "POST", UriTemplate = "...", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
Stream Create(Contract c);
此外,该服务还具有以下属性:
Also, the service is decorated with following attribute:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
谢谢. JF
推荐答案
WCF(自4.5版开始)不支持将任意JSON反序列化为数据协定的一部分.您需要使用另一个实现此目的的序列化程序-JSON.NET是我个人喜欢的序列化程序.为了能够更改序列化程序,可以使用其他消息格式化程序,并在
WCF (as of 4.5) doesn't support deserializing arbitrary JSON as part of a data contract. You'll need to use another serializer which does that - JSON.NET is one which I personally like. To be able to change the serializer, you can use a different message formatter, and in the post at http://blogs.msdn.com/b/carlosfigueira/archive/2011/05/03/wcf-extensibility-message-formatters.aspx I have a sample which does exactly that - replaces the default serialization used by WCF with JSON.NET.
请注意,要使用该库接收任意JSON,您需要将"json"属性的类型更改为与JSON.NET,JToken中的任意JSON等效:
Notice that to receive arbitrary JSON using that library, you'll need to change the type of the "json" property to the equivalent of arbitrary JSON in JSON.NET, JToken:
public class Contract
{
[DataMember]
public int clientId;
[DataMember]
public Newtonsoft.Json.Linq.JToken json;
}
这篇关于如何使用带有json动态成员的WCF DataContract的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!