使用 ObjectMapper 更改字段大小写 [英] Change field case with an ObjectMapper

查看:29
本文介绍了使用 ObjectMapper 更改字段大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我需要创建一个专家 ObjectMapper 并且找不到任何示例代码来启动这个过程.

I think I need to create a specialist ObjectMapper and cannot find any sample code to start the process.

JSON 的创建者使用 .Netpublic 属性,因此使用带有大写首字母的字段名称.我正在将 JSON 解析为 POJO,因此我想使用小写首字母.

The creator of the JSON is using .Net and public properties and therefore uses field names with an uppercase initial. I am parsing the JSON into POJOs so I would like to use a lowercase initial.

最后:

    public class Facet
    {
        public string Name { get; set; }
        public string  Value { get; set; }
    }

因此,在我结束时,我必须:

At my end I must therefore have:

    public class Facet {
        public String Name;
        public String Value;
    }

我更喜欢:

    public class Facet {
        public String name;
        public String value;
    }

这可以用 ObjectMapper 完成,我说得对吗?

Am I right that this could be done with an ObjectMapper?

推荐答案

使用 @JsonProperty 注释可以非常简单地解决您的第一个问题:

Your first issue can be addressed very simply with the @JsonProperty annotation:

// java-side class
public class Facet
{
    @JsonProperty("Name")
    public String name;

    @JsonProperty("Value")
    public String value;
}

现在 ObjectMapper 将匹配不同大小写的字段名称.如果你不想在你的类中添加注解,你可以创建一个 Mix-in 类来 stand in 为你的 Facet :

Now the ObjectMapper will match up the differently-cased field names. If you don't want to add annotations into your classes, you can create a Mix-in class to stand in for your Facet:

public class FacetMixIn
{
    @JsonProperty("Name")
    public String name;

    @JsonProperty("Value")
    public String value;
}

objectMapper.getDeserializationConfig().addMixInAnnotations(Facet.class, FacetMixIn.class);

这将实现相同的目的,而无需在您的 Facet 类中添加额外的注释.

This will achieve the same thing, without requiring additional annotations in your Facet class.

这篇关于使用 ObjectMapper 更改字段大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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