/*** String to Json ***/
JSONArray jsonArray = new JSONArray(str);
JSONObject jsonObject = new JSONObject (str);
/*** Json to String ***/
jsonArray.toString;
jsonObject.toString;
/***jsonArray String To List***/
//1 gson
List<Object> list = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<Object>>() {}.getType());
//2 jackson 要求较高 会抛异常
List<Person> personList = new ObjectMapper().readValue(jsonArray.toString(), new TypeReference<List<Person>>() {});
* 条件:一字符串格式要正确 key不能用单引号,双引号需要转义 也可以通过JSONObject或JSONArray的toString方法
* 第二 有且仅有一个无参构造方法 即不用显示写构造方法
* 第三 有属性的set方法 【不一定】 但一定要求键值与属性名完全一致
* 第四 如果是内部类需要是static 非内部类不要求static
/***List To jsonArray***/
//1 com.micsun.communication.util.json;
JSONArray jsonArray = JSONUtils.BeanList2JSONArray(list, Close.class);//list里面是close实体对象
//2 <dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>0.9</version>
</dependency>
JSONArray js = JSONArray.fromObject(listName);
/***jsonObject String to Map****/
//1 native
Map<String, Object> map = new HashMap<>();
JSONObject jsonObject = new JSONObject(jsonString);
for(String key : jsonObject.keySet()) { //****error****//
map.put(key, jsonObject.get(key));
}
//2 gson
Map<String, Object> map = new Gson().fromJson(jsonString, new TypeToken<Map<String,Object>>() {}.getType());
//3 com.alibaba.fastjson.JSON
Map map = (Map) JSON.parse(jsonString);
Map map = (Map) JSON.parseObject(jsonString);
Map map = (Map) JSON.parseObject(jsonString,Map.class);
//3 com.alibaba.fastjson.JSONObject
Map map = (Map) com.alibaba.fastjson.JSONObject.parse(jsonString);
Map map = (Map) com.alibaba.fastjson.JSONObject.parseObject(jsonString);
Map map = (Map) com.alibaba.fastjson.JSONObject.parseObject(jsonString,Map.class);
//4 Jackson 要求较高 会抛异常
Map<String, Object> map = new ObjectMapper().readValue(jsonString, new TypeReference<Map<String, Object>>(){});
/*** Map to JSON ***/
//1 native
JSONObject jsonObject = new JSONObject(map);
//2 gson
String jsonString = new Gson().toJson(map);
//3 jackson 会抛异常 要求高
String jsonString = new ObjectMapper().writeValueAsString(map);
/*** Entity to Json[string] ***/
//1 native
JSONObject jsonObject = new JSONObject(person);
//2 gson
String jsonString = new Gson().toJson(person);
//3 jackson 会抛异常 要求高
String jsonString = new ObjectMapper().writeValueAsString(person);
//4 com.micsun.communication.util.json
JSONObject jsonObject1 = JSONUtils.Bean2JSONObject(close);
/*** Json to Entity **/
//1 native
Person person = new Person(jsonObject.getString("name"), jsonObject.getInt("age"));
//2 gson
Person person = new Gson().fromJson(jsonString, Person.class);// 不要求只有无参构造
//3 jackson 会抛异常 要求高
Student person = new ObjectMapper().readValue(jsonObject.toString(), Student.class);