json
- json转字符串
JSON.TOJSONString(json)
- json串转对象
2.1 java自带的原生sf.json
import net.sf.json.JSONObject
String response="{\"status\":\"error\",\"message\":\"没有选中文件!\"}";
JSONObject jsonObject=JSONObject.fromObject(response);
String documentId=(String) jsonObject.get("message");
JSONObject jsonObject = new JSONObject(JSON字符串);
2.2 阿里巴巴的fastjson
import com.alibaba.fastjson.JSON
HashMap al = (HashMap)JSON.parseObject(JSON字符串,HashMap.class);
PersonalVo user = (PersonalVo)JSON.parseObject(JSON字符串,PersonalVo.class);
List<类型> list=JSON.parseArray(JSON字符串,类型.class);
对象转json字符串
String json=JSON.toJSONString(要转换的对象)
2.3 Gson解析
json字符转对象
Student stu = new Gson().fromJson(json, Student.class);
对象转json字符串
String json = new Gson().toJson(对象)
2.4 Jackjson解析
Student stu = new ObjectMapper().readValue(json字符串, Student .class);
参考:json字符串转对象的几种方式
3. list转json
Object o = JSON.toJSON(list);
String s = o.toString();
System.out.println(s);
4.json转对象 / 集合 / 实体类
// 如果转为数组
List<Response> informContents = JSON.parseArray(json, Response.class);
// 如果是对象
Response response = JSONObject.parseObject(json, Response.class);