How to handle Relaxed JSON parsing in Java

I’m dealing with a situation where an API response provides JSON data, but the keys aren’t enclosed in quotes. Instead of getting a standard JSON format, I receive something like {key: "value"}. I understand this is referred to as relaxed JSON.

For instance, here’s how the data looks:

{
  user: "johndoe",
  contact: "[email protected]",
  years: 30
}

When I attempt to parse this using Java libraries like Gson or Jackson, it results in errors due to the unquoted keys. I’m looking for advice on how to process such non-standard JSON in Java. Are there specific libraries or methods that can help manage this kind of relaxed JSON structure?

Jackson handles this out of the box if you set it up right. Just enable ALLOW_UNQUOTED_FIELD_NAMES in your ObjectMapper config. I hit this same problem with a legacy API that returned broken JSON. Here’s what fixed it:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

This makes Jackson more lenient with JSON format and accepts unquoted field names. You might also need ALLOW_SINGLE_QUOTES if the API uses single quotes for strings. Jackson’s way more flexible than Gson for handling wonky JSON formats, especially when you can’t control the API.

You could also preprocess the JSON to clean it up before parsing. I’ve hit this same issue with multiple APIs that send malformed JSON - regex replacement works great across different scenarios. Just use String.replaceAll() to wrap those unquoted keys in quotes before sending it to your parser. Try jsonString.replaceAll("(\w+):", "\"$1\":") to convert your relaxed format to proper JSON. This gives you more control over the transformation and works with any JSON library without special setup. There’s a bit more processing overhead, but it’s basically nothing for most cases and makes your code way more portable.

gson works for this too if you’d rather use it than jackson. just use gsonbuilder with setlenient() and it’ll handle your relaxed json no problem. i’ve been doing this for years with apis that don’t follow proper json standards.