How to parse JSON with unquoted property names in Java

I’m working with an API that gives me JSON responses, and I’ve noticed that some property names are not enclosed in quotes. For instance, rather than receiving a response like {"status": "success"}, I get something that looks like {status: "success"} where the keys are missing their quotation marks.

String apiResponse = "{message: 'Hello World', code: 200, active: true}";
// Standard JSON parser encounters an issue here
ObjectMapper mapper = new ObjectMapper();
// An exception occurs due to unquoted keys
MyObject result = mapper.readValue(apiResponse, MyObject.class);

I realize that this format is referred to as relaxed JSON or HJSON, but I’m struggling to find a way to parse it effectively in Java. The usual JSON libraries, such as Jackson, typically throw errors for unquoted property names. What is the best approach to manage this unusual JSON format? Are there specific libraries or configuration options that can help with this?

Had this exact issue last year with a legacy system spitting out malformed JSON. Jackson’s got you covered with JsonParser.Feature configurations. Just enable ALLOW_UNQUOTED_FIELD_NAMES when you create your ObjectMapper.

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

That second line handles single quotes around string values like in your example. Worked perfectly for me and didn’t add another dependency. Performance was way better than manually preprocessing the string too.

yeah, jackson handles this pretty well. you can also try gson with setLenient(true) if jackson isn’t working for some reason. I’ve used both and they parse that relaxed json format without much trouble. just remember to handle the single quotes properly too.

Been there with third-party APIs that can’t be bothered to follow JSON standards. Beyond the Jackson config already mentioned, you could try preprocessing if you need more control. Regex replacement works well for simple cases - just quote the unquoted keys before sending to your parser. Gets messy with nested objects and arrays though. The org.json library is another route - it’s way more forgiving with broken JSON. Not as powerful as Jackson, but handles these edge cases better right out of the gate. Whatever you pick, make sure you’re validating the transformed data. Relaxed parsing can hide real corruption issues.