akourt
akourt

Reputation: 5573

Way to turn invalid Json to valid

I am working on a project with a SonicWall router. The responses that I get from it are in json format. I have no problems parsing them etc, etc but it seems that there is one case where the SW will return an invalid json as a response. Here is an example:

{
    "success": false,
    "reboot_required": false,
    "status": [
        {
            "cli": [
                { "command": [ { "token": "no" }, { "token": "nat-policy" }, { "token": "id", "error": true }, { "token": "10", "error": true } ] },
                { "command": [ { "token": "end" } ] }
            ],
            "info": [
                 { "type": "error", "code": "CLI_E_NOT_FOUND", "message": "Nat Policy not found.
" }
            ]
        }
    ]
}

Notice that the message does not close properly but changes a line? This causes the following parsingException:

Exception in thread "main" javax.json.stream.JsonParsingException: Unexpected char 13 at (line no=11, column no=97, offset=447)
    at org.glassfish.json.JsonTokenizer.unexpectedChar(JsonTokenizer.java:532)
    at org.glassfish.json.JsonTokenizer.readString(JsonTokenizer.java:189)
    at org.glassfish.json.JsonTokenizer.nextToken(JsonTokenizer.java:376)
    at org.glassfish.json.JsonParserImpl$ObjectContext.getNextEvent(JsonParserImpl.java:261)
    at org.glassfish.json.JsonParserImpl$StateIterator.next(JsonParserImpl.java:172)
    at org.glassfish.json.JsonParserImpl.next(JsonParserImpl.java:149)
    at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:177)
    at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:143)
    at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:180)
    at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:143)
    at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:180)
    at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:103)

Is there any way to turn this in a valid json?

Upvotes: 1

Views: 8776

Answers (1)

Braj
Braj

Reputation: 46881

Get the json response and replace all new lines first before parsing it to object.

response.replaceAll("\r?\n", "");

Sample code using GSON API

    String json = "{\"msg\" : \"Hello \n World\"}";
    System.out.println(json);

    json = json.replaceAll("\r?\n", "");

    Map<String, String> map = new Gson().fromJson(json, new TypeToken<Map<String, String>>(){}.getType());
    System.out.println("Actual message:" + map.get("msg"));

Output:

{"msg" : " Hello 
 World"}
Actual message: Hello  World

Upvotes: 3

Related Questions