3 回答

TA贡献1825条经验 获得超4个赞
您可以使用JsonAnySetter JsonAnyGetter注释。后面可以使用Map
实例。如果您总是one-key-object
可以Collections.singletonMap
在其他情况下使用HashMap
或其他实现中使用。下面的示例显示了您可以轻松地使用这种方法并根据key
需要创建任意数量的随机 -s:
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!"}

TA贡献1784条经验 获得超9个赞
您可以将所有可能的名称作为变量,并对它们进行注释,以便在为 null 时忽略它们。这样,您只能在 JSON 中获取具有值的
然后更改您的设置器以输入映射到您想要的键的变量。
class Value {
@JsonProperty("val")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String val;
@JsonProperty("new_key")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String newKey;
@JsonProperty("any_random_string")
@JsonInclude(JsonInclude.Include.NON_NULL)
private String anyRandomString;
public void setVal(String s) {
if(/* condition1 */)
this.val = s;
else if (/* condition2 */) {
this.newKey = s;
} else if (/* condition3 */) {
this.anyRandomString = s;
}
}
}

TA贡献1835条经验 获得超7个赞
好问题@Prasad,这个答案与 JAVA 或 SPRING BOOT 无关,我只是提出这个答案,因为我搜索过使用 node 来做到这一点,并希望这能以某种方式帮助某人。在 JAVASCRIPT 中,我们可以为 JSON 对象添加动态属性名称,如下所示
var dogs = {};
var dogName = 'rocky';
dogs[dogName] = {
age: 2,
otherSomething: 'something'
};
dogName = 'lexy';
dogs[dogName] = {
age: 3,
otherSomething: 'something'
};
console.log(dogs);
但是当我们需要动态更改名称时,我们必须
得到那个属性
并创建另一个具有相同内容和新名称的属性
并从 JSON 中删除旧属性
将新属性分配给 JSON
除此方法外,还有另一种动态更改 JSON 名称的方法,在此先感谢
添加回答
举报