我们如何使JSON属性名称动态化。例如
public class Value { @JsonProperty(value = "value") private String val; public void setVal(String val) { this.val = val; } public String getVal() { return val; } }
序列化此对象时,它另存为,{"value": "actual_value_saved"}但我想使键也像一样动态{"new_key": "actual_value_saved"}。任何帮助深表感谢。
{"value": "actual_value_saved"}
{"new_key": "actual_value_saved"}
您可以使用JsonAnySetter JsonAnyGetter批注。您可以在后面使用Map实例。万一您总是one- key- object可以Collections.singletonMap在其他情况下使用HashMap或其他实现。下面的示例显示了使用此方法并根据需要创建任意数量的key-s是多么容易:
Map
one- key- object
Collections.singletonMap
HashMap
key
import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Collections; import java.util.Map; import java.util.Objects; public class JsonApp { public static void main(String[] args) throws Exception { DynamicJsonsFactory factory = new DynamicJsonsFactory(); ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(factory.createUser("Vika"))); System.out.println(mapper.writeValueAsString(factory.createPhone("123-456-78-9"))); System.out.println(mapper.writeValueAsString(factory.any("val", "VAL!"))); } } class Value { private Map<String, String> values; @JsonAnySetter public void put(String key, String value) { values = Collections.singletonMap(key, value); } @JsonAnyGetter public Map<String, String> getValues() { return values; } @Override public String toString() { return values.toString(); } } class DynamicJsonsFactory { public Value createUser(String name) { return any("name", name); } public Value createPhone(String number) { return any("phone", number); } public Value any(String key, String value) { Value v = new Value(); v.put(Objects.requireNonNull(key), Objects.requireNonNull(value)); return v; } }
上面的代码打印:
{"name":"Vika"} {"phone":"123-456-78-9"} {"val":"VAL!"}