package com.apobates.forum.utils.lang;

import com.apobates.forum.utils.Commons;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.util.Optional;

/**
 * CommonDoubleBean 类的jackson反序列化器
 * 
 * @author xiaofanku
 * @since 20200914
 */
public class CommonDoubleBeanDeserializer extends StdDeserializer<CommonDoubleBean>{
    private static final long serialVersionUID = 1L;
    
    public CommonDoubleBeanDeserializer() {
        super(CommonDoubleBean.class);
    }
    
    public CommonDoubleBeanDeserializer(JavaType valueType) {
        super(valueType);
    }
    
    public CommonDoubleBeanDeserializer(StdDeserializer<?> src) {
        super(src);
    }
    
    @Override
    public CommonDoubleBean deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
        JsonNode jn = new ObjectMapper().readTree(jp);
        //
        int id = Commons.stringToInteger(()->jn.get("id").toString(), 0);
        String title = Optional.ofNullable(jn.get("title").textValue()).orElse("-");
        double value = Commons.stringToDouble(()->jn.get("value").toString(), 0.0);
        return new CommonDoubleBean(id, title, value);
    }
}