将 JsonMediaTypeFormatter 应用于 Json



我有以下格式化程序

JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
formatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
formatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

我想在序列化对象时应用此格式

var jsonString = JsonConvert.SerializeObject(obj, formatter);

但是,我收到一个错误,指出

Cannot convert from System.Net.Http.Formatting.JsonMediaTypeFormatter to Newtonsoft.Json.Formatting

尝试以下操作,它在我的情况下工作正常:

// Create a Serializer with specific tweaked settings, like assigning a specific ContractResolver
var newtonSoftJsonSerializerSettings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore, // Ignore the Self Reference looping
PreserveReferencesHandling = PreserveReferencesHandling.None, // Do not Preserve the Reference Handling
ContractResolver = new CamelCasePropertyNamesContractResolver(), // Make All properties Camel Case
Formatting = Newtonsoft.Json.Formatting.Indented
};
// To the final serialization call add the formatter as shown underneath
var result = JsonConvert.SerializeObject(obj,newtonSoftJsonSerializerSettings.Formatting);

var result = JsonConvert.SerializeObject(obj,Newtonsoft.Json.Formatting.Indented);

在实际代码中,这就是我们使用具有特定设置的Json serializer的方式,对于 MVC 项目,使用上面创建的newtonSoftJsonSerializerSettings

// Fetch the HttpConfiguration object
HttpConfiguration jsonHttpconfig = GlobalConfiguration.Configuration;    
// Add the Json Serializer to the HttpConfiguration object
jsonHttpconfig.Formatters.JsonFormatter.SerializerSettings = newtonSoftJsonSerializerSettings;
// This line ensures Json for all clients, without this line it generates Json only for clients which request, for browsers default is XML
jsonHttpconfig.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

因此,所有Http requests都使用相同的序列化程序(newtonSoftJsonSerializerSettings(进行序列化。

最新更新