JSONObject jsonObject = new JSONObject(); String msg = "{ ["level"]=1, ["power"]=25, ["icon"]="equip2020016", ["color"]=0, ["des"]="equipd20016", }"; jsonObject.put("msg", msg); System.out.println(jsonObject.toString());
Exception in thread "main" java.lang.ClassCastException: JSON keys must be strings. at net.sf.json.JSONObject._fromJSONObject(JSONObject.java:1067) at net.sf.json.JSONObject.fromObject(JSONObject.java:177) at net.sf.json.JSONSerializer.toJSON(JSONSerializer.java:108) at net.sf.json.JSONObject._processValue(JSONObject.java:2759) at net.sf.json.JSONObject._setInternal(JSONObject.java:2817) at net.sf.json.JSONObject.element(JSONObject.java:1892) at net.sf.json.JSONObject.element(JSONObject.java:1869) at net.sf.json.JSONObject.put(JSONObject.java:2485) at com.log.record.Log.main(Log.java:11)
这个msg 其实是其他地方传过来的String对象。如果直接put就报错了。
需要进行一次转换才可正常序列化。
public static String String2Json(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.toCharArray()[i]; switch (c) { case '"': sb.append("\""); break; case '\': sb.append("\\"); break; case '/': sb.append("\/"); break; case '': sb.append("\b"); break; case 'f': sb.append("\f"); break; case ' ': sb.append("\n"); break; case ' ': sb.append("\r"); break; case ' ': sb.append("\t"); break; default: if ((c >= 0 && c <= 31) || c == 127)// 在ASCⅡ码中,第0~31号及第127号(共33个)是控制字符或通讯专用字符 { } else { sb.append(c); } break; } } return sb.toString(); }
也可使用谷歌的处理方式
public class JsonTest { public static void main(String[] args){ String ss = "{"headTrCode":"030500D600","headUserId":"batch_user_id","headCustNo":"batch_cust_no"}"; TbspResponse response = new Gson().fromJson(ss,TbspResponse.class); System.out.println(response.getHeadChannel()); String tt = new Gson().toJson(response); System.out.println(tt); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser parser = new JsonParser(); JsonElement je = parser.parse(tt.toString()); String result = gson.toJson(je); TbspResponse response2 = new Gson().fromJson(ss,TbspResponse.class); System.out.println(response.getHeadChannel()); } }