Skip to content

Gson – MalformedJSONException Fix

Gson – MalformedJSONException fix example shows what is MalformedJSONException and how to fix it while using the Gson library in Java. This example also shows how to solve the MalformedJSONException using various methods.

What is MalformedJSONException and when is it thrown?

As the name suggests, the MalformedJSONException occurs when we try to read/parse JSON data that is invalid or not in the proper format. The problem could be because the JSON objects and/or JSON arrays are not opened or closed properly, presence of the invalid characters, unterminated string values, or any other formatting issues.

When Gson encounters any such invalid JSON data, it throws com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException while reading/parsing it.

The below given JSON is not valid. The value of the “name” property is not terminated properly due to missing double quotes.

When we try to parse this JSON using the Gson, it will throw com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException.

Output

How to solve MalformedJSONException?

Solution 1:

Make sure that the input JSON is in a valid format. We can use a service like https://jsonlint.com to validate the JSON. If it is invalid, fix the issue in the input JSON to fix the MalformedJsonException.

Solution 2:

Sometimes the input source adds extra characters at the end of the JSON object that are not whitespace characters. The JSON only considers ‘\n’, ‘r’, and ‘\t’ as whitespace characters. Any characters other than these after the end of the JSON object, for example, a null character ‘\0’, will cause the MalformedJsonException.

A simple fix to remove these characters from the input JSON is to use the trim method.

Solution 3:

If the first two solutions do not work, we can set the JSON parsing in a lenient mode that allows JSON data that does not strictly comply with the JSON specification.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.