假设我有一个 bean:
public class Msg {
private int code;
private Object data;
... Getter/setters...
}
我使用这种测试代码将其转换为 JSON 或 XML:
public String convert() {
Msg msg = new Msg();
msg.setCode( 42 );
msg.setData( "Are you suggesting coconuts migrate?" );
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString( msg );
}
输出将是这样的:
{"code":42,"data":"Are you suggesting coconuts migrate?"}
现在假设我想用一些动态名称替换“数据”属性:
public String convert(String name) {
Msg msg = new Msg();
msg.setCode( 42 );
msg.setData( "Are you suggesting coconuts migrate?" );
ObjectMapper mapper = new ObjectMapper();
// ...DO SOMETHING WITH MAPPER ...
return mapper.writeValueAsString( msg );
}
如果我调用函数convert("toto")我希望得到这个输出:
{"code":42,"toto":"Are you suggesting coconuts migrate?"}
如果我调用函数convert("groovy")我希望得到这个输出:
{"code":42,"groovy":"Are you suggesting coconuts migrate?"}
当然,我可以在创建 JSON 后进行字符串替换,但如果您有程序化方法的答案,我会接受。
谢谢