序列化JSON Rest服务时加密自定义对象字段

时间:2019-02-21 23:10:10

标签: java json serialization infinite

亲爱的

我被困在这里:

在Spring 4.3.3.RELEASE中,尝试使用来自objectMapper的JsonSerializer加密对象数量(自定义对象)的一个字段

我已经设置了

@Override
public void configureMessageConverters(
    List<HttpMessageConverter<?>> converters) {
    //Added string converter to avoid scape " and the addition of " at the beginning of the Json
    converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
    converters.add(new MappingJackson2HttpMessageConverter(objectMapper));

}

objectmapper在此类中定义

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.registerModule(new JodaMoneyModule());
    objectMapper.registerModule(new JodaModule());
    //objectMapper.registerModule(new AmountModule());
    objectMapper.getFactory().setCharacterEscapes(new JavascriptCharacterEscapes());
    return objectMapper;

}

AmountModule是我的自定义序列化

public class AmountModule extends SimpleModule
{
    private static final long serialVersionUID = 1L;

    public AmountModule()
    {
        super();

        // then serializers:
        addSerializer(Amount.class, new AmountSerializer());

    }
}

public class AmountSerializer extends JsonSerializer<Amount> {

    @Override
    public void serialize(Amount amount, JsonGenerator jgen, SerializerProvider provider) throws IOException,  JsonProcessingException {
        if (amount!=null) {
            try {
                amount.setValue(webParamEncryptor.encryptWebParam(amount.getValue().toPlainString()));
                jgen.writeObject(amount);
            } catch (Exception e) {
                logger.error("Error to marshal date", e);
            }
        } else {
            jgen.writeNull();
        }

    }
}

我的对象金额如下:

 public class Amount extends Currency {
    private static final long serialVersionUID = 1L;

    @JsonProperty("value")
    private String value = null;

    @JsonProperty("customDisplay")
    private String customDisplay = null;

    private boolean roundToCurrencyDecimals= true;

余额对象使用量

public class Account implements Serializable {
private static final long serialVersionUID = 1L;

@JsonProperty("id")
private int id;

@JsonIgnore
private String number = null;

@JsonIgnore
private Amount balance = null;

序列化帐户时,出现以下错误:

无法写入内容:无限递归(StackOverflowError)(通过参考链:java.util.ArrayList [0]-> accounts.domain.Account [\“ balance \”]); < / p>

我尝试了所有@JsonIgnore / @JsonView / @JsonManagedReference,@JsonBackReference}和@JsonIdentityInfo / @JsonIdentityInfo,但似乎没有任何用处,或者可能是我将东西放置在错误的位置。

能帮我些忙吗?谢谢

0 个答案:

没有答案