杰克逊JSON漂亮的打印使用注释

时间:2017-03-01 08:20:42

标签: java json jackson lagom jackson-databind

我正在使用@JSONCreator@JsonCreator将响应bean转换为Lagom Framework中的JSON。但是,JSON没有格式化。如何使用注释(而不是ObjectMapper)打印JSON?这是我的示例响应bean:

@Immutable
@JsonDeserialize
public class foo {

  private final List<Result> _result;

  private final MetadataBean _meta;

  @JsonCreator
  public foo (List<Result> _result, MetadataBean _meta) {
    this._result= _result;
    this._meta = _meta;
  }

}

1 个答案:

答案 0 :(得分:1)

似乎漂亮的打印由ObjectMappercannot be influenced by annotations控制。 negotiated serializers的Lagom文档有这个例子:

public class JsonTextSerializer implements MessageSerializer.NegotiatedSerializer<String, ByteString> {
    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public MessageProtocol protocol() {
        return new MessageProtocol(Optional.of("application/json"), Optional.empty(), Optional.empty());
    }

    @Override
    public ByteString serialize(String s) throws SerializationException {
        try {
            return ByteString.fromArray(mapper.writeValueAsBytes(s));
        } catch (JsonProcessingException e) {
            throw new SerializationException(e);
        }
    }
}

然后可以在mapper上启用漂亮的打印(可能在构造函数中):

mapper.enable(SerializationFeature.INDENT_OUTPUT);