gpt4 book ai didi

java - Jackson - 在没有注释的情况下在运行时修改属性

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:50:52 26 4
gpt4 key购买 nike

假设我有一个 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 后进行字符串替换,但如果您有编程方法的答案,我会接受它。

谢谢

最佳答案

您可以使用 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?"}

关于java - Jackson - 在没有注释的情况下在运行时修改属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18915630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com