Parsing non-standard JSON format in Java

Hey everyone,

I’m having trouble with a JSON response I got from an API. The problem is that some of the keys in the JSON aren’t wrapped in quotes. I think this might be called ‘Relaxed JSON’ or something similar.

Here’s a snippet of what I’m dealing with:

{
  name: "John Doe",
  age: 30,
  city: "New York"
}

As you can see, the keys (name, age, city) aren’t in quotes. This is causing issues when I try to parse it in Java.

Does anyone know how to handle this kind of JSON in Java? Are there any libraries or methods that can parse this non-standard format? I’ve been scratching my head over this for hours now.

Any help or suggestions would be really appreciated. Thanks in advance!

hey pete, i’ve run into this before. you might wanna check out the gson library. it’s pretty forgiving with non-standard json. just add it to ur project and use the GsonBuilder class with lenient parsing enabled. should handle those unquoted keys no prob. good luck!

I’ve dealt with this kind of non-standard JSON before in a project. While libraries like Gson and Jackson are solid choices, I found JSONObject from org.json to be a simple yet effective solution. It’s quite lenient with parsing and can handle unquoted keys without any extra configuration.

Here’s a quick example of how you could use it:

String jsonStr = "{ name: \"John Doe\", age: 30, city: \"New York\" }";
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
String city = jsonObj.getString("city");

Just add the org.json dependency to your project, and you’re good to go. It’s straightforward and gets the job done without much fuss. Hope this helps!

I’ve encountered similar issues with non-standard JSON formats. One effective solution I’ve used is the Jackson library with its ALLOW_UNQUOTED_FIELD_NAMES feature. Here’s how you can implement it:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
YourObject obj = mapper.readValue(jsonString, YourObject.class);

This configuration allows Jackson to parse JSON with unquoted keys. It’s robust, widely used, and integrates well with most Java projects. Remember to add the Jackson dependency to your project before using it. This approach has saved me countless hours of frustration when dealing with non-standard JSON responses.