您还可以在 POJO 类中添加“Strings”、“Intigers”等的其他 getter。这些方法应返回Map
's 作为结果。考虑下面的代码:
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"
}
}
这可能不是您可以使用的最优雅的解决方案,但它很简单。