Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

java - Change field case with an ObjectMapper

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

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.

At their end:

    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;
    }

I would much prefer:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

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);

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...