at the project I am working on, we have a requirement to have a DataContract that can contain some undefined 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.
Example:
public class Contract
{
[DataMember]
public int clientId;
[DataMember]
public string json;
}
Obviously, having a contract defined like that would require the client to escape the json like this:
{
"clientId":1,
"json": "{\"test\":\"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:
Does anyone have a possible solution to this problem?
EDIT
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)]
Thank you. JF
No, the DataContractAttribute is not required - WCF will infer serialization rules.
A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts.
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 https://github.com/microsoftarchive/msdn-code-gallery-community-s-z/tree/master/Supporting%20different%20data%20and%20serialization%20formats%20in%20WCF I have a sample which does exactly that - replaces the default serialization used by WCF with JSON.NET.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With