运行Jar文件触发GSON MalformedJsonException,Eclipse中运行正常求助
Hey there, let's take a look at your JSON parsing method and iron out some potential issues that might be causing you trouble (or could lead to problems down the line):
1. Outdated JsonParser usage
Assuming you're using Gson (given the method names like getAsJsonObject), the new JsonParser().parse(event) approach is deprecated in newer versions of Gson. It's better to use the Gson instance's fromJson method instead—it's more maintainable and aligns with current library standards.
2. Missing null/existence checks
Your code directly chains calls like jelement.getAsJsonObject() and obj.getAsJsonObject("from") without verifying if those elements actually exist or are of the correct type. If the input JSON doesn't have a "from" object, or if the root element isn't a JSON object at all, this will throw a NullPointerException right away. While your catch block will catch it, proactive checks make the code more robust and avoid unnecessary exceptions.
3. Overly broad exception handling
Catching Exception swallows all possible errors—including things like thread interrupts or out-of-memory errors—that have nothing to do with JSON parsing. It's better to catch only the specific exceptions related to your logic, like JsonSyntaxException (for invalid JSON) and IllegalStateException (for type mismatches).
4. Ambiguous error return value
Returning "-1" as an error marker is risky: if the actual field value is supposed to be the string "-1", you won't be able to tell if it's a valid result or an error. A cleaner approach is to return an Optional<String>—this makes it explicit to the caller whether the field was successfully retrieved.
Here's an improved version of your method that addresses all these points:
import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import java.util.Optional; public static Optional<String> getFieldFrom(String field, String event) { Gson gson = new Gson(); try { JsonObject rootObj = gson.fromJson(event, JsonObject.class); // Check if root is a valid object and contains the "from" field as an object if (rootObj == null || !rootObj.has("from") || !rootObj.get("from").isJsonObject()) { return Optional.empty(); } JsonObject fromObj = rootObj.getAsJsonObject("from"); // Check if target field exists and is a string primitive if (fromObj.has(field) && fromObj.get(field).isJsonPrimitive() && fromObj.get(field).getAsJsonPrimitive().isString()) { return Optional.of(fromObj.get(field).getAsString()); } return Optional.empty(); } catch (JsonSyntaxException e) { System.err.println("Invalid JSON format when parsing event: " + e.getMessage()); } catch (IllegalStateException e) { System.err.println("Failed to access field '" + field + "': " + e.getMessage()); } return Optional.empty(); }
How to use this improved method
Callers can now handle both success and failure cases clearly:
Optional<String> fieldValue = getFieldFrom("email", eventJson); if (fieldValue.isPresent()) { // Use the value System.out.println("Retrieved field: " + fieldValue.get()); } else { // Handle missing/invalid field System.out.println("Field not found or invalid"); }
内容的提问来源于stack exchange,提问作者Mirco Ianese

