需要json_simple-1.1.jar 包
public static void main(String[] args) {
//1 json对象转换为字符串
JSONObject subObject = new JSONObject();
subObject.put("ooo", "***");
subObject.put("ppp", "&&&");
JSONObject object = new JSONObject();
object.put("aaa", "111");
object.put("bbb", "222");
object.put("ccc", subObject);
System.out.println(object.toJSONString());
//2 json数组对象装换为字符串
JSONArray array = new JSONArray();
JSONObject object1 = new JSONObject();
object1.put("aaa", "111");
object1.put("bbb", "222");
JSONObject object2 = new JSONObject();
object2.put("aaa", "111");
object2.put("bbb", "222");
array.add(object1);
array.add(object2);
System.out.println(array.toJSONString());
//3 字符串转换为json对象
String jsonStr = "{\"aaa\":\"111\",\"ccc\":\"***\",\"bbb\":\"222\"}";
JSONParser parser = new JSONParser();
try {
JSONObject parseObject = (JSONObject)parser.parse(jsonStr);
System.out.println("json对象---->" + parseObject.toJSONString());
} catch (ParseException e) {
e.printStackTrace();
}
//4 字符串转换为数组
jsonStr = "[{\"aaa\":\"111\",\"bbb\":\"222\"},{\"aaa\":\"111\",\"bbb\":\"222\"}]";
try {
JSONArray parseObject = (JSONArray)parser.parse(jsonStr);
System.out.println("数组---->" + parseObject.toJSONString());
} catch (ParseException e) {
e.printStackTrace();
}
}