JSON序列化中属性名称的默认驼峰大小写

v64noz0r  于 2023-03-31  发布在  其他
关注(0)|答案(8)|浏览(272)

我有一堆类,它们将在某个时候被序列化为JSON,为了在后端遵循C#约定,在前端遵循JavaScript约定,我定义了这样的属性:

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

在C#中,我们可以:

MyFoo = 10;

在Javascript中,我可以:

if (myFoo === 10)

但是对每个属性都这样做是很繁琐的,有没有一种快速简单的方法来设置JSON.Net处理属性名的默认方式,这样除非另有说明,否则它会自动大小写转换?

wrrgggsh

wrrgggsh1#

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

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

换句话说,您不必自己创建自定义冲突解决程序。

nxagd54h

nxagd54h2#

序列化对象时,传入一些自定义设置。

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

var json = JsonConvert.SerializeObject(yourObject, settings);
sqxo8psd

sqxo8psd3#

最好使用新的CamelCaseNamingStrategy(自9.0.1起):

new JsonSerializerSettings()
{
    ContractResolver = new DefaultContractResolver
    {
       NamingStrategy = new CamelCaseNamingStrategy()
    }
};

默认情况下,它不会覆盖由属性JsonProperty("Name")设置的自定义名称。(您可以通过CamelCaseNamingStrategy(bool, bool) ctor更改行为。)因此,不需要像@Matt Burland的答案那样创建自定义类。

7rtdyuoh

7rtdyuoh4#

JObject.FromObject使用来自JsonConvert默认值的默认设置。您可以像这样分配func属性:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
 {
   ContractResolver = new CamelCasePropertyNamesContractResolver()
 };

无论何时调用Jobject.FromObject,它都会使用这个函数来构造设置。

gcuhipw9

gcuhipw95#

由于接受的答案是仅链接,所以我添加了我最终使用的实际代码(以防链接死亡)。它与链接中的内容基本相同:

// Automatic camel casing because I'm bored of putting [JsonProperty] on everything
// See: http://harald-muehlhoff.de/post/2013/05/10/Automatic-camelCase-naming-with-JsonNET-and-Microsoft-Web-API.aspx#.Uv43fvldWCl
public class CamelCase : CamelCasePropertyNamesContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member,
        MemberSerialization memberSerialization)
    {
        var res = base.CreateProperty(member, memberSerialization);

        var attrs = member.GetCustomAttributes(typeof(JsonPropertyAttribute), true);

        if (attrs.Any())
        {
            var attr = (attrs[0] as JsonPropertyAttribute);
            if (res.PropertyName != null && attr.PropertyName != null)
                res.PropertyName = attr.PropertyName;
        }

        return res;
    }
}

我所做的唯一更改是在if子句中添加了attr.PropertyName != null,因为我在这里添加了如下内容:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string SomeProperty { get; set; }

并且不想指定PropertyName(所以它是null)。上面的内容将在JSON中序列化为someProperty

cygmwpex

cygmwpex6#

您可以使用自定义contract resolver

class MyContractResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var properties = base.CreateProperties(type, memberSerialization);

        foreach (var property in properties)
        {
            property.PropertyName = char.ToLower(property.PropertyName[0]) + string.Join("", property.PropertyName.Skip(1));
        }

        return properties;
    }
}

像这样使用它:

class MyClass
{
    public int MyProperty { get; set; }
    public int MyProperty2 { get; set; }
}

var json = JsonConvert.SerializeObject(new MyClass(), 
                Formatting.Indented, 
                new JsonSerializerSettings { ContractResolver = new MyContractResolver() });
8wigbo56

8wigbo567#

在.NET 5.0中,您可以使用System.Text.Json并在JsonSerializerOptions中指定PropertyNamingPolicy
System.Text.Json.JsonSerializerOptions.PropertyNamingPolicy
这里有一个指向Microsoft文档页面的链接,该页面将属性设置为使用 Camel 大小写。

var serializeOptions = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = true
};
jsonString = JsonSerializer.Serialize(weatherForecast, serializeOptions);

班级

public class WeatherForecastWithPropertyNameAttribute
{
    public DateTimeOffset Date { get; set; }
    public int TemperatureCelsius { get; set; }
    public string Summary { get; set; }
    [JsonPropertyName("Wind")]
    public int WindSpeed { get; set; }
}

JSON输出

{
  "date": "2019-08-01T00:00:00-07:00",
  "temperatureCelsius": 25,
  "summary": "Hot",
  "Wind": 35
}
goqiplq2

goqiplq28#

public static JsonSerializer FormattingData()
{
   var jsonSerializersettings = new JsonSerializer {
   ContractResolver = new CamelCasePropertyNamesContractResolver() };
   return jsonSerializersettings;
}

public static JObject CamelCaseData(JObject jObject) 
{   
     var expandoConverter = new ExpandoObjectConverter();
     dynamic camelCaseData = 
     JsonConvert.DeserializeObject(jObject.ToString(), 
     expandoConverter); 
     return JObject.FromObject(camelCaseData, FormattingData());
}

相关问题