Jackson - 将 java 对象转换为 json - 需要将所有键都大写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11049174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hymanson - converting java object to json - Need all key keys to upper case
提问by Asif
Need your help on conversion of java objects to json. current the json result showing all the key in small letter case, i need it to be upper case.
在将 java 对象转换为 json 时需要您的帮助。当前以小写字母显示所有键的 json 结果,我需要它是大写的。
ObjectMapper mapper = new ObjectMapper();
Writer strWriter = new StringWriter();
mapper.writeValue(strWriter, obj);
String jsonString= strWriter.toString();
and the result is
结果是
[{"flags":"1","name":"Peter","location":"London","startDate":"2012-01-06 00:00"}]
but i want results like this (all key key value should be in UPPER CASE):
但我想要这样的结果(所有关键键值都应该大写):
[{"FLAGS":"YU","NAME":"Peter","LOCATION":"London","STARTDATE":"2012-01-06 00:00"}]
and also is it possible to get like this also (key first letter in upper case):
并且也有可能得到这样的结果(大写的关键第一个字母):
[{"Flags":"1","Name":"Peter","Location":"London","StartDate":"2012-01-06 00:00"}]
Can anyone help me on this.
谁可以帮我这个事。
Thanks in advance.
提前致谢。
回答by KARASZI István
There are multiple ways to do it with Hymanson.
Hymanson 有多种方法可以做到这一点。
Annotations
注释
You could annotate your object with @JsonProperty
annotationson your fields or on your getter methods.
您可以在您的字段或 getter 方法上使用@JsonProperty
注释来注释您的对象。
Example:
例子:
@JsonProperty("Name")
public final String name;
@JsonProperty("Location")
public String getLocation() {
return location;
}
Implement JsonSerializableWithType interface
实现 JsonSerializableWithType 接口
@Override
public void serialize(final JsonGenerator jG, final SerializerProvider p)
throws IOException, JsonProcessingException
{
serializeWithType(jG, p, null);
}
@Override
public void serializeWithType(final JsonGenerator jG, final SerializerProvider p, final TypeSerializer typeSer)
throws IOException, JsonProcessingException
{
// here you can do your own serialization
}
回答by keiki
I would advice to use the @JsonNaming
annotation on class level.
我建议@JsonNaming
在类级别使用 注释。
Yet afaik there is no strategy out there to fit your needs for total uppercase. But you can probably just write your own.
然而,afaik 没有任何策略可以满足您对全部大写的需求。但你可能只写自己的。
In my case I needed first character uppercase. So I used the existing
@JsonNaming(value = UpperCamelCaseStrategy.class)
.
就我而言,我需要第一个字符大写。所以我使用了现有的
@JsonNaming(value = UpperCamelCaseStrategy.class)
.