본문 바로가기
  • A space that records me :)
Language/JAVA

[JAVA] JsonUtils

by yjkim_97 2021. 5. 10.
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.boot.json.JsonParseException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;



public class JsonUtils {
	public static String parseJsonObject(Object obj) throws JsonProcessingException {
		ObjectMapper mapper = new ObjectMapper();
		DefaultSerializerProvider sp = new DefaultSerializerProvider.Impl();
		sp.setNullValueSerializer(new NullSerializer());
		mapper.setSerializerProvider(sp);
		
		return mapper.writeValueAsString(obj);

	}
	
	
	public static List<Map<String, Object>> parseStringAsList(String str) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();
		List<Map<String, Object>> dtlList = null;
		dtlList = mapper.readValue(str, new TypeReference<List<Map<String, Object>>>(){});
		return dtlList;
	}
	
	public static JsonNode parseString(String str) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();
		return mapper.readValue(str, JsonNode.class);
	}
	
	public static JsonNode parseObject(Object obj) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();
		return mapper.valueToTree(obj);
	}
	
	public static <T> T parseString(String str, Class<T> classType) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();
		return mapper.readValue(str, classType);
	}
	
	public static <T> T parseString(JsonNode jsonNode, Class<T> classType) throws JsonParseException, JsonMappingException, IOException{
		ObjectMapper mapper = new ObjectMapper();
		return mapper.readValue(parseJsonObject(jsonNode), classType);
	}

	public static class NullSerializer extends JsonSerializer<Object> {
        public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString("");
        }
    }
}

'Language > JAVA' 카테고리의 다른 글

[JAVA] HttpUtil  (0) 2021.12.19
[JAVA] java에서 shell command 실행  (0) 2021.11.24
[JAVA] PropertyDescriptor 클래스  (0) 2020.11.30
[JAVA] ReflectionUtil  (0) 2020.11.30
[JAVA] AES256, SHA256 - 암호화 복호화  (0) 2020.11.30