JSON Parser
Parse and validate JSON with custom error handling
Description
A JSON parsing utility with validation, error handling, and type conversion. Provides safe parsing with detailed error messages.
Features
- Safe parsing
- Error handling
- Type conversion
- Validation
Code
import com.google.gson.Gson;import com.google.gson.JsonSyntaxException;import com.google.gson.reflect.TypeToken;import java.lang.reflect.Type;import java.util.Map;public class JsonParser { private static final Gson gson = new Gson(); public static <T> T parse(String json, Class<T> clazz) throws JsonParseException { try { return gson.fromJson(json, clazz); } catch (JsonSyntaxException e) { throw new JsonParseException("Invalid JSON syntax: " + e.getMessage(), e); } } public static <T> T parse(String json, Type type) throws JsonParseException { try { return gson.fromJson(json, type); } catch (JsonSyntaxException e) { throw new JsonParseException("Invalid JSON syntax: " + e.getMessage(), e); } } public static Map<String, Object> parseToMap(String json) throws JsonParseException { Type type = new TypeToken<Map<String, Object>>(){}.getType(); return parse(json, type); } public static String toJson(Object obj) { return gson.toJson(obj); } public static boolean isValid(String json) { try { gson.fromJson(json, Object.class); return true; } catch (JsonSyntaxException e) { return false; } } public static class JsonParseException extends Exception { public JsonParseException(String message, Throwable cause) { super(message, cause); } }}
import JsonParser.*;public class Example { public static void main(String[] args) { String json = "{"name":"John","age":30}"; // Validate if (isValid(json)) { System.out.println("Valid JSON"); // Parse to Map try { Map<String, Object> map = parseToMap(json); System.out.println("Parsed: " + map); } catch (JsonParseException e) { System.err.println("Parse error: " + e.getMessage()); } } else { System.out.println("Invalid JSON"); } }}
Comments
No comments yet. Be the first to comment!
Please login to leave a comment.