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

时间:2013-09-20 11:26:49

标签: java json jackson

假设我有一个豆子:

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创建后进行字符串替换,但是如果你有一个程序化方法的答案,我会接受它。

由于

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:4)

一种可能性是使用所谓的“任何吸气剂”:

public class Msg {
  public int code;

  @JsonAnyGetter
  public Map<String,Object> otherFields() {
    Map<String,Object> extra = new HashMap<String,Object>();
    extra.put("data", findDataObject()); // or whatever mechanism you want
    extra.put("name", "Some Name");
    return extra;
  }
}

这样您就可以返回任意一组动态属性。

您还可以使用匹配的“任何getter”(@JsonAnyGetter)机制来接受其他属性。