Tips:只有光头才能强~
{ "pid":100000671319, "sessionId":"2323-23", "content":"评论了商品“23护眼角防晒口罩”" ,"jsonData":"{\"aid\":100000671319,\"goodsName\":\"护眼角防晒口罩\",\"goodslist\":\"[{\\\"id\\\":1428903181}]\"}","createTime":1658147346012 }
每次遇到这个问题,报json格式不正确。都吵的不可开交,心累。不如两分钟写一个递归解析。
伪代码如下:
static Object strTojson(String js){
if(js.startsWith("{")){
return jsonStrObjTojson(JSONObject.parseObject(js));
}else if (js.startsWith("[")){
return jsonStrArrTojson(JSON.parseArray(js));
}
return js;
}
static JSON jsonStrObjTojson(JSONObject jo){
for (Map.Entry<String, Object> entry : jo.entrySet()) {
if (entry.getValue() instanceof String) {
entry.setValue(strTojson(entry.getValue().toString()));
}else if (entry instanceof JSONArray) {
entry.setValue(jsonStrArrTojson((JSONArray) entry.getValue()));
}else if (entry instanceof JSONObject) {
entry.setValue(jsonStrObjTojson((JSONObject) entry.getValue()));
}
}
return jo;
}
static JSON jsonStrArrTojson(JSONArray ja){
ja.forEach(e->{
if (e instanceof String) {
ja.remove(e);
ja.add(strTojson(e.toString()));
}else if (e instanceof JSONArray) {
ja.remove(e);
ja.add(jsonStrArrTojson((JSONArray)e));
}else if (e instanceof JSONObject) {
ja.remove(e);
ja.add(jsonStrObjTojson((JSONObject) e));
}
});
return ja;
}
public static void main(String[] args) {
String json="{ \"pid\":100000671319, \"sessionId\":\"2323-23\", \"content\":\"评论了商品“23护眼角防晒口罩”\" ,\"jsonData\":\"{\\\"aid\\\":100000671319,\\\"goodsName\\\":\\\"护眼角防晒口罩\\\",\\\"goodslist\\\":\\\"[{\\\\\\\"id\\\\\\\":1428903181}]\\\"}\",\"createTime\":1658147346012 }";
System.out.println(strTojson(json));
}
欢迎提出意见,有更好的工具或者更快的算法,请在评论区留言
json包用的fastjson
如果文章对您有帮助,扫个红包码呗