假设我有一个豆子:
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?"}
现在,假设我想用一些动态名称替换“ data”属性:
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创建后执行String替换,但是如果您对程序化方法有一个满意的答案,我会接受。
谢谢
您可以使用 PropertyNamingStrategyclass覆盖class属性。查看此类的简单实现:
PropertyNamingStrategy
class ReplaceNamingStrategy extends PropertyNamingStrategy { private static final long serialVersionUID = 1L; private Map<String, String> replaceMap; public ReplaceNamingStrategy(Map<String, String> replaceMap) { this.replaceMap = replaceMap; } @Override public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) { if (replaceMap.containsKey(defaultName)) { return replaceMap.get(defaultName); } return super.nameForGetterMethod(config, method, defaultName); } }
示例程序如下所示:
import java.io.IOException; import java.util.Collections; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.cfg.MapperConfig; import com.fasterxml.jackson.databind.introspect.AnnotatedMethod; public class JacksonProgram { public static void main(String[] args) throws IOException { Msg msg = new Msg(); msg.setCode(42); msg.setData("Are you suggesting coconuts migrate?"); System.out.println(convert(msg, "test")); System.out.println(convert(msg, "toto")); System.out.println(convert(msg, "groovy")); } public static String convert(Msg msg, String name) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(new ReplaceNamingStrategy(Collections.singletonMap("data", name))); return mapper.writeValueAsString(msg); } }
上面的程序打印:
{"code":42,"test":"Are you suggesting coconuts migrate?"} {"code":42,"toto":"Are you suggesting coconuts migrate?"} {"code":42,"groovy":"Are you suggesting coconuts migrate?"}