简体   繁体   English

名称中混合驼峰时如何从JSON [反]序列化为pojo对象

[英]How to [de]serialize to pojo objects from JSON when there is mixed camel case in names

I'm using Dropwizard (which uses Jackson under the hood) to create a bridging API service. 我正在使用Dropwizard(在后台使用Jackson)创建桥接API服务。 It connects to two other API's that are very similar (API1 and API2). 它连接到两个非常相似的其他API(API1和API2)。

I have my own POJO library that contains the request and response POJO's for API1 and API2. 我有自己的POJO库,其中包含API1和API2的请求和响应POJO。 The only difference between those two API's is that for certain objects API1 emits capitalised keys, whereas the other doesn't. 这两个API之间的唯一区别是,对于某些对象,API1会发出大写的键,而其他对象则不会。 Basically one API1 is implemented in Java and API2 is implemented in .NET but both serve the same data. 基本上,一个API1用Java实现,而API2用.NET实现,但是两者都提供相同的数据。

{
    "Name" : "foo",
    "Address" : "bar"
}

versus

{
    "name" : "foo",
    "address" : "bar"
}

I want to avoid writing a POJO class for each one when otherwise they are identical objects. 我想避免为每个对象编写一个POJO类,否则它们是相同的对象。

What is the correct way to tell Jackson to accept either name? 告诉杰克逊接受任何一个名字的正确方法什么?

I'm aware of @JsonProperty eg 我知道@JsonProperty例如

@JsonProperty("Name")
private String name;

However even if this works for both "name" and "Name", it feels a bit untidy. 但是,即使这对“名称”和“名称”均适用,也感觉有些不整洁。 To me, declaring this annotation should effectively mean ignore the coded field name in favour of the annotation. 对我来说,声明此批注应该实际上意味着忽略编码字段名,而使用该批注。

Thanks in advance 提前致谢

You may take a look at PropertyNamingStrategy which you can define for the ObjectMapper in use. 您可以看一下可以为使用中的ObjectMapper定义的PropertyNamingStrategy

You could define different strategies for different service consumers (when you are the producer) if the other side is not flexible regarding the convention used (does not accept both upper- and lowercase forms). 如果另一方在使用的约定方面不灵活(不接受大写和小写形式),则可以为不同的服务使用者(当您是生产者)定义不同的策略。

If you can afford to use Jackson 2.5, then you could take a look at mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true) 如果您有能力使用Jackson 2.5,那么可以看看mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true)

For full control over Jackson (de)serialization process, take a loot at custom serialization and custom deserialization . 要完全控制杰克逊(反)序列化过程,请在自定义序列化自定义反序列化过程中优先使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM