Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.util.*; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationFeature; public class Main { public static ObjectMapper mapper = new ObjectMapper() { private static final long serialVersionUID = -174113593500315394L; { configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } }; /** * JSON Deserialization of the given json string. * @param json The json string to deserialize * @param <T> The type of the object to deserialize into * @return The deserialized object */ public static <T extends Object> T deserialize(String json, TypeReference<T> typeReference) throws IOException { if (isNullOrWhiteSpace(json)) return null; return mapper.readValue(json, typeReference); } /** * JSON Deserialization of the given json string. * @param jParser The json parser for reading json to deserialize * @param <T> The type of the object to deserialize into * @return The deserialized object */ public static <T extends Object> T deserialize(JsonParser jParser, Class<T> typeReference) throws IOException { if ((null == jParser) || (jParser.isClosed())) return null; return mapper.readValue(jParser, typeReference); } /** * JSON Deserialization of the given json string. * @param json The json string to deserialize * @return The deserialized json as a Map */ public static LinkedHashMap<String, Object> deserialize(String json) throws IOException { if (isNullOrWhiteSpace(json)) return null; TypeReference<LinkedHashMap<String, Object>> typeRef = new TypeReference<LinkedHashMap<String, Object>>() { }; return deserialize(json, typeRef); } /** * Validates if the string is null, empty or whitespace * @param s The string to validate * @return The result of validation */ public static boolean isNullOrWhiteSpace(String s) { if (s == null) return true; int length = s.length(); if (length > 0) { for (int start = 0, middle = length / 2, end = length - 1; start <= middle; start++, end--) { if (s.charAt(start) > ' ' || s.charAt(end) > ' ') { return false; } } return true; } return false; } }