可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I want to convert jnvalid JSON data into 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 valid JSON data formatted as below:
{ "name": "date", "order": "1", "required": "true", "type": "date", "placeholder": "Expense Date" }
回答1:
I'm not going to do it for you as you haven't provided any code to what you have done but I will guide you on how to do it. Iterate over the file or the string whatever you have it on, line by line. Then instantiate a string builder to keep appending the valid JSON to. append the first quote to the string builder, then use line.split(':') on a single line to get an array with the 1st half of the line and the second half. Then append the splitLine[0] (1st half) onto the string builder, append the colon, append the 2nd half of the line splitLine[1] and finally append the last quote and the comma. Now do this for every line and you will have valid JSON.
Here is a working version of what I explained above.
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);
The bit at the end may look a little confusing
i==lineByLine.length-1?"}":","
But what it is doing is checking if it's the last line of JSON close it with a bracket, otherwise place a comma ready for the next attribute
回答2:
you can use replaceAll and 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 + '}';
回答3:
it can be done by splitting string by “:”