给定以下类,
public class Result
{
public bool Success { get; set; }
public string Message { get; set; }
}
我在Controller操作中返回其中的一个,如下所示
return Json(new Result() { Success = true, Message = "test"})
但是,我的客户端框架希望这些属性是小写的成功和消息。实际上不必使用小写的属性名,这是一种通过正常的Json函数调用来实现这一点的方法吗?
发布于 2014-03-28 19:25:23
使用我的解决方案,您可以重命名任何您想要的属性。
我已经找到了解决方案here的一部分,等等
public class JsonNetResult : ActionResult
{
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult(object data, Formatting formatting)
: this(data)
{
Formatting = formatting;
}
public JsonNetResult(object data):this()
{
Data = data;
}
public JsonNetResult()
{
Formatting = Formatting.None;
SerializerSettings = new JsonSerializerSettings();
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data == null) return;
var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
var serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
所以在我的控制器中,我可以做到这一点
return new JsonNetResult(result);
在我的模型中,我现在可以:
[JsonProperty(PropertyName = "n")]
public string Name { get; set; }
请注意,现在,您必须将JsonPropertyAttribute
设置为要序列化的每个属性。
发布于 2019-01-30 14:32:39
您可以将此设置添加到Global.asax
,它将在任何地方运行。
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
//....
JsonConvert.DefaultSettings = () =>
{
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
PreserveReferencesHandling = PreserveReferencesHandling.None,
Formatting = Formatting.None
};
return settings;
};
//....
}
}
发布于 2018-04-20 17:45:27
虽然这是一个老问题,但希望下面的代码片段能对其他人有所帮助,
我在下面用MVC5网络应用编程接口做了。
public JsonResult<Response> Post(Request request)
{
var response = new Response();
//YOUR LOGIC IN THE METHOD
//.......
//.......
return Json<Response>(response, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() });
}
https://stackoverflow.com/questions/2789593
复制相似问题