问题描述
只是想知道是否有办法做到这一点 - 我有一个类,比如
Just wondering if there was a way to do this - I have a class, something like
class MyClass {
private String name;
private String address;
private String number;
}
当我使用Jackson将其序列化为Json时,我想要包装字符串变量在一起,所以它看起来像
When I serialise it to Json, using Jackson, I want to wrap the String variables together, so it would look something like
{
"Strings": {
"name" : "value",
"address" : "value"
}
}
没有将这些变量包装在MyClass中的List或Map类中......这可能吗?
Without wrapping those variables in a List or Map class inside the MyClass... is this possible?
推荐答案
你也可以在你的POJO课程中为Strings,Intigers等添加额外的getter。这些方法应该返回 Map
的结果。请考虑以下代码:
You can also add into your POJO class additional getters for "Strings", "Intigers", etc. Those methods should return Map
's as a result. Consider below code:
import java.util.LinkedHashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonProgram {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
MyClass myClass = new MyClass();
myClass.setAddress("New York, Golden St. 1");
myClass.setName("James Java");
myClass.setNumber("444");
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(myClass));
}
}
class MyClass {
private String name;
private String address;
private String number;
@JsonIgnore
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonIgnore
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@JsonIgnore
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
@JsonProperty(value = "Strings")
public Map<String, String> getStrings() {
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("name", getName());
map.put("address", getAddress());
map.put("number", getNumber());
return map;
}
}
结果:
{
"Strings" : {
"name" : "James Java",
"address" : "New York, Golden St. 1",
"number" : "444"
}
}
这可能是您可以使用的最优雅的解决方案,但它很简单。
This is not, probably, the most elegant solution which you can use, but it is simple.
这篇关于Java& Json:序列化时包装元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!