gpt4 book ai didi

c# - 将 JsonMediaTypeFormatter 应用于 Json

转载 作者:太空狗 更新时间:2023-10-29 23:36:26 26 4
gpt4 key购买 nike

我有以下格式化程序

 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 序列化程序,对于 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请求都使用相同的序列化器(newtonSoftJsonSerializerSettings)序列化

关于c# - 将 JsonMediaTypeFormatter 应用于 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45843432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com