JSON序列化中属性名称的默认驼峰式 [英] Default camel case of property names in JSON serialization

查看:958
本文介绍了JSON序列化中属性名称的默认驼峰式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆类将在某些时候序列化为JSON,并且为了遵循后端的C#约定和前端的JavaScript约定,我一直在定义如下属性:

I have a bunch of classes that will be serialized to JSON at some point and for the sake of following both C# conventions on the back-end and JavaScript conventions on the front-end, I've been defining properties like this:

[JsonProperty(PropertyName="myFoo")]
public int MyFoo { get; set; }

这样,在C#中,我可以:

So that in C# I can:

MyFoo = 10;

在Java语言中,我可以:

And in Javascript I can:

if (myFoo === 10)

但是对每个属性执行此操作都很繁琐.是否有一种快速简便的方法来设置JSON.Net处理属性名称的默认方式,以便除非另行通知,否则它将自动使用驼峰式大小写?

But doing this for every property is tedious. Is there a quick and easy way to set the default way JSON.Net handles property names so it will automatically camel case unless told otherwise?

推荐答案

您可以使用提供的类 Newtonsoft .Json.Serialization.CamelCasePropertyNamesContractResolver :

var serializer = new JsonSerializer
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};
var jobj = JObject.FromObject(request, serializer);

换句话说,您不必自己创建自定义解析器.

In other words, you don't have to create a custom resolver yourself.

这篇关于JSON序列化中属性名称的默认驼峰式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆