John
John

Reputation: 281

JSON checker to avoid com.google.gson.stream.MalformedJsonException

I'm getting many JSON objects through a web service and at times the json object is malformed.

I wanted to check the if the json is valid before processing it.

So i worte

JsonElement jsonData = parser.parse(attacheddataattribute);
if(jsonData.isJsonObject()) 
                {
//then only process
}

Not also its throwing a com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 8432 at the parse method.

Is there any implemenation available to check for the JSON's validity.

Upvotes: 0

Views: 3379

Answers (2)

SilverTech
SilverTech

Reputation: 429

I also had the MalformedJsonException crash but in my case I needed to add a catch block with Throwable:

    fun jsonToList(value: String?): MutableList<String> {
        var objects: Array<String> = emptyArray()
        try {
            objects = Gson().fromJson(value, Array<String>::class.java)
        }catch (t: Throwable){

        }finally {
            return objects.toMutableList()
        }
    }

Upvotes: 0

Enrichman
Enrichman

Reputation: 11337

That's your validation. No need to call any service.

If the method is throwing the MalformedJsonException it's a malformed JSON.

If you want you can wrap it in a method like

public boolean isValidJson(String json) {
    try {
        // parse json
        return true;
    } catch(MalformedJsonException e) {
        return false;
    }
}

Upvotes: 2

Related Questions