【发布时间】:2011-03-02 03:22:43
【问题描述】:
我需要向 wcf 休息服务 (4.0) 发出发布请求。该服务将从客户端应用程序(jquery)和服务器端应用程序(asp.net 等)调用。 该服务公开一个持久存储并提供 CRUD 操作。
我对序列化有疑问。
我看了几篇与此相关的文章-> http://blogs.msdn.com/b/youssefm/archive/2009/04/21/understanding-known-types.aspx
public class CustomType
{
public Dictionary<string,object> CustomObjectCollection {get; set;}
public SavedBy {get; set;}
public SavedOn {get; set;}
public CustomType()
{
CustomObjectCollection = new Dictionary<string,object>();
}
}
public class State1
{
public prop1 {get; set;}
public prop2 {get; set;}
}
public class State2
{
public prop1 {get; set;}
public prop2 {get; set;}
}
客户端使用 WCF:
public void save()
{
CustomType req = new CustomType();
req.CustomObjectCollection("State1", new State1() {prop1 = val1, prop2 = val2 } );
req.CustomObjectCollection("State2", new State2() {prop1 = val3, prop2 = val4 } );
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CustomType));
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, setting);
string json = Encoding.Default.GetString(ms.ToArray());
ms.Close();
Utility.HTTPRequest("http://localhost:2222/MyWCFRestSVC/save", "post", json);
}
WCF 方法:
public bool Save(CustomType req)
{
/////////
}
我可能无法使用“已知类型”解决方法,因为使用此服务的每个客户端都将使用其自己的自定义类型。理想情况下,服务不应该担心客户想要保留的类型。请注意,该服务公开了一个仅保存通用状态信息的持久性存储。
我尝试使用 Dictionary 而不是 Dictionary 我将 json 字符串表示 os State1 和 State2 存储为值。我遇到的问题是,当我使用 DataContractJsonSerializer 序列化 CustomType 实例时,State1 和 State2 的 json 字符串嵌入了反斜杠(转义字符),我猜是因为双重序列化?
我有关于自定义序列化而不是 DataContractJsonSerializer 的想法。
请告诉我你的想法。
感谢您的宝贵时间。
【问题讨论】:
标签: c# wcf json serialization rest