morningPerson
morningPerson

Reputation: 23

Convert Invalid Json to Valid Json

I have an invalid Json which has 2 double quoutes at value of "actualdeliverytime". I tried using JsonObject but it throws invalid Json error. I solved issue with this sdata.substring(0,sdata.length()-2)+"}"; approach. Is there a way to get valid json by using regex? I am newbie, sorry if it's very basic question.

{
    "actualdeliverydate": "20210505",
    "actualdeliverytime": "091812""
}

Upvotes: 1

Views: 3531

Answers (2)

Ironluca
Ironluca

Reputation: 3782

This is more of a workaround and not really something you should do in production. In addition, the JSON generation should be fixed at the source. Having said that (only for the case you provided), replace consecutive double quote with a single double quote with string replace. Refer the implementation below:

package org.test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class InvalidJSONTest {

    public static void main(String[] args) throws Exception{
        
        String invalid="{\r\n" + 
                "    \"actualdeliverydate\": \"20210505\",\r\n" + 
                "    \"actualdeliverytime\": \"091812\"\"\r\n" + 
                "}";
        
        String mayBeValid=invalid.replaceAll("\"\"", "\"");
        
        System.out.println(mayBeValid);
        
        ObjectMapper mapper=new ObjectMapper();
        
        JsonNode node=mapper.readValue(mayBeValid.getBytes(), JsonNode.class);
        
        System.out.println(node.get("actualdeliverytime").asText());

    }//main closing

}//class closing

Upvotes: 1

IntoVoid
IntoVoid

Reputation: 964

Just do:

String valid_json = invalid_json.replaceAll("(\"(?:[^\"]|\\\\\")*\")\"", "$1");

Upvotes: 0

Related Questions