gpt4 book ai didi

java - Jackson - 在运行时修改属性而无需注释

转载 作者:行者123 更新时间:2023-12-01 18:08:19 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?"}

现在假设我想用一些动态名称替换“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 后进行字符串替换,但如果您有通过编程方法得到的答案,我会接受。

谢谢

最佳答案

您可以使用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/60515820/

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