亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何包裝杰克遜序列化異常

如何包裝杰克遜序列化異常

一只萌萌小番薯 2023-09-06 17:09:46
Jackson如果其中一個 getter 拋出異常,如何序列化對象?例子:public class Example {     public String getSomeField() {          //some logic which will throw in example NPE          throw new NullPointerException();     }}理想情況下我想得到JSON:{"someField":"null"}或者{"someField":"NPE"}
查看完整描述

1 回答

?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

最通用的方法可能是實現 custom BeanPropertyWriter。您可以通過創建類來注冊它BeanSerializerModifier。下面的示例展示了如何做到這一點。


import com.fasterxml.jackson.core.JsonGenerator;

import com.fasterxml.jackson.databind.BeanDescription;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.databind.SerializationConfig;

import com.fasterxml.jackson.databind.SerializerProvider;

import com.fasterxml.jackson.databind.module.SimpleModule;

import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;

import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;


import java.util.List;

import java.util.stream.Collectors;


public class JsonApp {


    public static void main(String[] args) throws Exception {

        SimpleModule module = new SimpleModule();

        module.setSerializerModifier(new BeanSerializerModifier() {

            @Override

            public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {

                if (beanDesc.getBeanClass() == Response.class) {

                    return beanProperties.stream()

                            .map(SilentExceptionBeanPropertyWriter::new)

                            .collect(Collectors.toList());


                }


                return super.changeProperties(config, beanDesc, beanProperties);

            }

        });


        ObjectMapper mapper = new ObjectMapper();

        mapper.registerModule(module);



        System.out.println(mapper.writeValueAsString(new Response(1, "ONE")));

        System.out.println(mapper.writeValueAsString(new Response(-1, "MINUS")));

        System.out.println(mapper.writeValueAsString(new Response(-1, null)));

    }

}


class SilentExceptionBeanPropertyWriter extends BeanPropertyWriter {


    public SilentExceptionBeanPropertyWriter(BeanPropertyWriter base) {

        super(base);

    }


    @Override

    public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {

        try {

            super.serializeAsField(bean, gen, prov);

        } catch (Exception e) {

            Throwable cause = e.getCause();

            gen.writeFieldName(_name);

            gen.writeString(cause.getClass().getName() + ":" + cause.getMessage());

        }

    }

}



class Response {


    private int count;

    private String message;


    public Response(int count, String message) {

        this.count = count;

        this.message = message;

    }


    public int getCount() {

        if (count < 0) {

            throw new IllegalStateException("Count is less than ZERO!");

        }

        return count;

    }


    public void setCount(int count) {

        this.count = count;

    }


    public String getMessage() {

        if (message == null) {

            throw new NullPointerException("message can not be null!");

        }

        return message;

    }


    public void setMessage(String message) {

        this.message = message;

    }

}

上面的例子打印:


{"count":1,"message":"ONE"}

{"count":"java.lang.IllegalStateException:Count is less than ZERO!","message":"MINUS"}

{"count":"java.lang.IllegalStateException:Count is less than ZERO!","message":"java.lang.NullPointerException:message can not be null!"}



查看完整回答
反對 回復 2023-09-06
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號