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

com.github.shoothzj.javatool.service.JacksonService Maven / Gradle / Ivy

There is a newer version: 3.1.15
Show newest version
package com.github.shoothzj.javatool.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class JacksonService {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    }

    public static String toJson(Object o) {
        try {
            return MAPPER.writeValueAsString(o);
        } catch (Exception e) {
            log.error("json process error, exception is ", e);
        }
        return "";
    }

    public static  T toObject(String json, Class type) {
        try {
            return MAPPER.readValue(json, type);
        } catch (Exception e) {
            log.error("json process error, exception is ", e);
        }
        return null;
    }

    public static  T toRefer(String json, TypeReference reference) {
        try {
            return MAPPER.readValue(json, reference);
        } catch (Exception e) {
            return null;
        }
    }

    public static  List toList(String json, TypeReference> typeReference) {
        try {
            return MAPPER.readValue(json, typeReference);
        } catch (Exception e) {
            return null;
        }
    }

    public static JsonNode toJsonNode(String json) {
        try {
            return MAPPER.readTree(json);
        } catch (Exception e) {
            return null;
        }
    }

    public static ObjectNode createObjectNode() {
        return MAPPER.createObjectNode();
    }

    public static ArrayNode createArrayNode() {
        return MAPPER.createArrayNode();
    }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy