简体   繁体   English

JSON的Java对象:字段名称

[英]Java objects to JSON: field names

I have a pretty standard Java POJO. 我有一个非常标准的Java POJO。 Let's call it Dog: 我们称之为狗:

Dog.java has a series of fields. Dog.java具有一系列字段。 In Java, convention says field names should start with a lower case. 在Java中,约定表示字段名称应以小写字母开头。 This means I have: 这意味着我有:

  • public String name; 公共字符串名称;
  • public String dogType; public String dogType;
  • public String weight; 公共字符串权重;

At the same time, I have a requirement on my JSON format that the JSON members (name, dogType, and weight) all be written with a capital letter at the beginning ie Name, DogType, and Weight. 同时,我对JSON格式有一个要求,即JSON成员(名称,dogType和权重)都必须在开头加上大写字母,即Name,DogType和Weight。

I am using Jackson. 我正在使用杰克逊。

If I use the standard serialization code as below, I get JSON member names written exactly the same way they are in Java. 如果使用下面的标准序列化代码,则会得到JSON成员名称,它们的书写方式与Java中的完全相同。

ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jReq);
System.out.println(json);

To address my problem, I have 2 options: 为了解决我的问题,我有2种选择:

  • either I use the Jackson annotation @JsonProperty(value="DogType") , or 我要么使用Jackson批注@JsonProperty(value="DogType") ,要么
  • I use a naming strategy as described in the API . 我使用API中所述的命名策略。

My question is: is there a clean way of doing it? 我的问题是:是否有一种干净的方法?

There are quite a few questions on SO about this that explain both ways: 关于SO的很多问题都可以解释这两种方式:

But none go into the pros and cons. 但是没有人会谈利弊。

My initial hunch is that I should go for the naming strategy. 我最初的预感是我应该采用命名策略。 Is that a good approach or a bad one? 这是好方法还是坏方法?

I think you should go for the naming strategy, too. 我认为您也应该采用命名策略。 The advantage of this one is that you can always override it with the annotations, if needed. 这一功能的优点是,如果需要,您始终可以使用注释覆盖它。

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

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