JavaScript字符串对象转JSON格式
JavaScript字符串对象转JSON格式
原始数据
{
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
}
java
代码
// js 对象转 json 串
public static String jsonObjToJSON(String jsonStr) {
StringBuffer sf = new StringBuffer();
String[] split = jsonStr.replace("'", "\"").split(":");
for (int j = 0; j < split.length; j++) {
String temp = split[j];
char[] chars = temp.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for (int i = chars.length - 1; i > 0; i--) {
int ch = chars[i];
if ((ch >= 65 && ch <= 90) | (ch >= 97 && ch <= 122)) {
stringBuilder.append(chars[i]);
} else {
break;
}
}
if (stringBuilder.length() != 0) {
StringBuilder reverse = stringBuilder.reverse();
String replace = temp.replace(reverse, "\"" + reverse + "\":");
split[j] = replace;
}
sf.append(split[j]);
}
return sf.toString();
}
public static void main(String[] args) {
String str="{\n" +
" xAxis: {\n" +
" type: 'category',\n" +
" data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']\n" +
" },\n" +
" yAxis: {\n" +
" type: 'value'\n" +
" },\n" +
" series: [\n" +
" {\n" +
" data: [150, 230, 224, 218, 135, 147, 260],\n" +
" type: 'line'\n" +
" }\n" +
" ]\n" +
"}";
System.out.println(jsonObjToJSON(str));
}
转换后的数据
{
"xAxis": {
"type": "category",
"data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
},
"yAxis": {
"type": "value"
},
"series": [
{
"data": [150, 230, 224, 218, 135, 147, 260],
"type": "line"
}
]
}
哇!又赚了一天人民币