Convert Invalid Json to a valid json android?

I want to convert jnvalid JSON data to valid JSON data. I have JSON like this below. Is there any logic to change it using Java?

 {
    name: date,
    order: 1,
    required: true,
    type: date,
    placeholder: Expense Date
}

I want JSON data to be formatted as follows:

{
    "name": "date",
    "order": "1",
    "required": "true",
    "type": "date",
    "placeholder": "Expense Date"
 }
+4
source share
3 answers

, , , , . , , . , JSON. , line.split(':') , . splitLine [0] (1- ) , , splitLine [1] , , . , JSON.

, .

String inputString = "name: date, order: 1, required: true, type: date, placeholder: Expense Date";
StringBuilder validJson = new StringBuilder();
validJson.append("{");
String[] lineByLine =  inputString.split(",");
for(int i =0; i< lineByLine.length; i++){
    String[] lineSplit = lineByLine[i].split(":");
    validJson.append('"').append(lineSplit[0].trim()).append('"').append(":").append('"').append(lineSplit[1].trim()).append('"').append(i==lineByLine.length-1?"}":",");
}
String finishedJSON = validJson.toString();
System.out.println(finishedJSON);

i==lineByLine.length-1?"}":","

, , - , JSON ,

+3

replaceAll regex:

String str = "{ name: date, order: 1, required: true, type: date, placeholder: Expense Date }";

/*remove '{' and '}' for trim*/
String trim = str.substring(1, str.length() - 1).trim();

/* x:y => "x":y */
trim = trim.replaceAll("([a-zA-Z0-9]+)(\\s*\\:)", "\\\"$1\\\"$2");

/* "x":y => "x":"y" */
trim = trim.replaceAll("(\\:\\s*)([a-zA-Z0-9\\s]+)", "$1\\\"$2\\\"");

str = '{' + trim + '}';
+1

this can be done by dividing the string by ":"

-1
source

Source: https://habr.com/ru/post/1690696/


All Articles