问题描述
我是一个有点新的WCF和会尽量清楚地描述我所试图做的。
I am a bit new to WCF and will try to clearly describe what I am trying to do.
我有一个使用JSON请求一个WCF web服务。我做的很好发送/接收JSON大部分。例如,下面的code运作良好,并预期。
I have a WCF webservice that uses JSON requests. I am doing fine sending/receiving JSON for the most part. For example, the following code works well and as expected.
JSON发送:
{ "guy": {"FirstName":"Dave"} }
WCF:
[DataContract]
public class SomeGuy
{
[DataMember]
public string FirstName { get; set; }
}
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
public string Register(SomeGuy guy)
{
return guy.FirstName;
}
这将返回与预期戴夫的JSON对象。问题是,我不能总是保证JSON我收到会成员完全符合我的DataContract。为例子,JSON:
This returns a JSON object with "Dave" as expected. The problem is that I cannot always guarantee that the JSON I recieve will exactly match the members in my DataContract. For example, the JSON:
{ "guy": {"firstname":"Dave"} }
将无法正确序列化,因为情况不符。 guy.FirstName将为空。这种行为很有道理,但我真的不知道该怎么来解决这个问题。我一定要逼字段名称在客户端上还是有办法,我可以在服务器端调和?
will not serialize correctly because the case does not match. guy.FirstName will be null. This behavior makes sense, but I don't really know how to get around this. Do I have to force the field names on the client or is there a way I can reconcile on the server side?
这可能是相关的问题:我可以接受的,而通用JSON对象序列化到StringDictionary或某种简单的键值结构?所以,不管是什么字段名发送的JSON,我可以访问的名称和已发送给我的价值观?现在,我可以读我收到的数据的唯一方法是,如果它完全pdefined DataContract一个$ P $相匹配。
A possibly related question: can I accept and serialize a generic JSON object into a StringDictionary or some kind of simple key value structure? So no matter what the field names are sent in the JSON, I can access names and values that have been sent to me? Right now, the only way I can read the data I'm receiving is if it exactly matches a predefined DataContract.
推荐答案
下面是读JSON入词典的另一种方式:
Here's an alternative way to read json into dictionary:
[DataContract]
public class Contract
{
[DataMember]
public JsonDictionary Registration { get; set; }
}
[Serializable]
public class JsonDictionary : ISerializable
{
private Dictionary<string, object> m_entries;
public JsonDictionary()
{
m_entries = new Dictionary<string, object>();
}
public IEnumerable<KeyValuePair<string, object>> Entries
{
get { return m_entries; }
}
protected JsonDictionary(SerializationInfo info, StreamingContext context)
{
m_entries = new Dictionary<string, object>();
foreach (var entry in info)
{
m_entries.Add(entry.Name, entry.Value);
}
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (var entry in m_entries)
{
info.AddValue(entry.Key, entry.Value);
}
}
}
这篇关于通用WCF JSON反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!