All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mokung.pomegranate.jackson.handler.getter.IntegerGetter Maven / Gradle / Ivy

There is a newer version: 1.0.2
Show newest version
package com.mokung.pomegranate.jackson.handler.getter;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.*;
import com.mokung.pomegranate.jackson.handler.Getter;

/**
 *
 * @author mokung
 */
public class IntegerGetter implements Getter {

    private static final Pattern NUMBER_WITH_TRAILING_ZEROS_PATTERN = Pattern.compile("\\.0*$");

    @Override
    public Integer getter(JsonNode valueNode, ObjectMapper mapper, boolean cast) {
        if (valueNode instanceof IntNode) {
            return valueNode.asInt();
        }
        if (!cast || valueNode == null || valueNode instanceof NullNode) {
            return null;
        }
        if (valueNode instanceof NumericNode) {
            return valueNode.asInt();
        }
        if (valueNode instanceof TextNode) {
            String value = valueNode.asText();
            return stringToInteger(value);
        }
        if (valueNode instanceof POJONode) {
            Object value = ((POJONode)valueNode).getPojo();
            if (value == null) {
                return null;
            }
            return stringToInteger(value.toString());
        }
        return null;
    }

    private Integer stringToInteger(String value) {
        if (value == null || value.length() <= 0 || value.trim().length() <= 0) {
            return null;
        }
        String splitChar = ",";
        if (value.contains(splitChar)) {
            value = value.replaceAll(splitChar, "");
        }
        Matcher matcher = NUMBER_WITH_TRAILING_ZEROS_PATTERN.matcher(value);
        if (matcher.find()) {
            value = matcher.replaceAll("");
        }
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            // ignore
        }

        return null;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy