I’m dealing with a situation where an API response contains JSON data that has property names without quotes. For instance, instead of receiving a response like { "name": "John", "age": 25 }, I get something that looks like {name: "John", age: 25} where the keys aren’t quoted.
I’ve found out that this is referred to as relaxed JSON, but I’m struggling to parse it using Java. When I try using common JSON libraries such as Jackson or Gson, they throw errors upon encountering these unquoted keys.
String apiResponse = "{userId: 123, userName: \"sampleUser\", isActive: true}";
// This leads to failure with standard parsers
ObjectMapper mapper = new ObjectMapper();
JsonNode result = mapper.readTree(apiResponse); // causes an exception
What is the recommended method to parse such malformed JSON in Java? Should I adjust the string to include quotes, or is there a specific parser that can accommodate this format?
Jackson actually supports this with JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES. Had the exact same problem with a legacy API that returned JavaScript object notation instead of proper JSON. Here’s how I fixed it: ObjectMapper mapper = new ObjectMapper(); mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); JsonNode result = mapper.readTree(apiResponse); This handles unquoted property names perfectly and I’ve never had issues with it. Way cleaner than regex preprocessing, which breaks on edge cases. The parser deals with malformed JSON gracefully and you still get type safety.
Gson can handle this too through GsonBuilder. Just enable lenient parsing and it’ll tolerate unquoted keys plus other non-standard JSON stuff. I hit this same problem with a third-party service that exported JavaScript objects instead of proper JSON. Fixed it by creating a custom Gson instance with setLenient(true). Here’s how: Gson gson = new GsonBuilder().setLenient().create(); YourObject result = gson.fromJson(apiResponse, YourObject.class); Works great and handles all kinds of malformed JSON, not just unquoted keys. Way better than trying to fix it with string manipulation.
Just preprocess the string with regex before parsing. Use apiResponse.replaceAll("(\w+):", "\"$1\":") to add quotes around keys. It’s hacky but sometimes the simple fix works best - no need to mess with parser configs.