将JsonMediaTypeFormatter应用于Json

blu*_*nha 5 c# json json.net

我有以下格式化程序

 JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
 formatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
 formatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
 formatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Run Code Online (Sandbox Code Playgroud)

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

 var jsonString = JsonConvert.SerializeObject(obj, formatter);
Run Code Online (Sandbox Code Playgroud)

但是,我得到一个错误说明

 Cannot convert from System.Net.Http.Formatting.JsonMediaTypeFormatter to Newtonsoft.Json.Formatting
Run Code Online (Sandbox Code Playgroud)

Mri*_*boj 3

尝试以下操作,在我的情况下效果很好:

// 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);
Run Code Online (Sandbox Code Playgroud)

或者

 var result = JsonConvert.SerializeObject(obj,Newtonsoft.Json.Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)

在实际代码中,这就是我们如何使用上面创建的Json serializerMVC 项目的特定设置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"));
Run Code Online (Sandbox Code Playgroud)

因此,所有这些Http requests都使用相同的序列化器(newtonSoftJsonSerializerSettings)进行序列化