C# 将WCF 4中的默认JSON序列化程序替换为JSON.NET
我想用JSON.NET替换默认的WCF JSON(适用于所有数据类型)序列化。 我在网上到处搜索,找不到有效的解决方案 这是我的目标:C# 将WCF 4中的默认JSON序列化程序替换为JSON.NET,c#,json,wcf,c#-4.0,json.net,C#,Json,Wcf,C# 4.0,Json.net,我想用JSON.NET替换默认的WCF JSON(适用于所有数据类型)序列化。 我在网上到处搜索,找不到有效的解决方案 这是我的目标: [JsonObject] public class TestObject { [JsonProperty("JsonNetName")] public string Name = "John"; [JsonProperty] public DateTime Date = DateTime.Now; } 这是我的WCF功
[JsonObject]
public class TestObject
{
[JsonProperty("JsonNetName")]
public string Name = "John";
[JsonProperty]
public DateTime Date = DateTime.Now;
}
这是我的WCF功能:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<TestObject> Get();
这是Web.Config:
<endpointBehaviors>
<behavior name="Behavior_Brands">
<webHttp defaultOutgoingResponseFormat="Json" defaultBodyStyle="Bare" />
</behavior>
</endpointBehaviors>
JSON答案显然忽略了JSON.NET属性。无论如何,我找到了一种手动使用不同序列化程序的方法,它似乎更高效、更快,因为它不通过Microsoft的序列化程序,尽管代码方面有点混乱
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
System.ServiceModel.Channels.Message GetData();
return yourObject.GetJsonStream();
什么样的测试结果表明它确实更快?不幸的是,对于我使用类似替代技术的测试用例(500KB对象层次结构),JSON.NET序列化的两个步骤加上复制到UTF8的字节数组不知何故使它比普通的DataContractJsonSerializer更昂贵:-(
[{"Date":"\/Date(1354364412708+0200)\/","Name":"John"}, {"Date":"\/Date(1354364412708+0200)\/","Name":"John"}]
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
System.ServiceModel.Channels.Message GetData();
public static System.ServiceModel.Channels.Message GetJsonStream(this object obj)
{
//Serialize JSON.NET
string jsonSerialized = JsonConvert.SerializeObject(obj);
//Create memory stream
MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(jsonSerialized));
//Set position to 0
memoryStream.Position = 0;
//return Message
return WebOperationContext.Current.CreateStreamResponse(memoryStream, "application/json");
}
return yourObject.GetJsonStream();