Json-lib
下载地址:https://sourceforge.net/projects/json-lib/files/json-lib/
JsonObject方式
String jsonString ="{\"id\":\"1\",\"name\":\"小明\",\"sex\":\"男\"}";
JSONObject json = JSONObject.fromObject(jsonString);
Student student = new Student();
student.setId(json.getString("id"));
student.setName(json.getString("name"));
student.setSex(json.getString("sex"));
System.out.println(student.toString());
JsonArray方式
String jsonString ="{\"id\":\"1\",\"name\":\"小明\",\"sex\":\"男\"},{\"id\":\"2\",\"name\":\"小红\",\"sex\":\"女\"}";
JSONArray jsonArray = JSONArray.fromObject(jsonString);
for (int i = 0; i < jsonArray.size(); i++) {
Student student = new Student();
student.setId(jsonArray.getJSONObject(i).getString("id"));
student.setName(jsonArray.getJSONObject(i).getString("name"));
student.setSex(jsonArray.getJSONObject(i).getString("sex"));
}
fastjson
下载地址:http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22fastjson%22
JsonObject方式
String jsonString = "{\"id\":\"1\",\"name\":\"小明\",\"sex\":\"男\"}";
JSONObject jo = JSONObject.parseObject(jsonString);
System.out.println(jo.getString("id"));
System.out.println(jo.getString("name"));
System.out.println(jo.getString("sex"));
JsonObject方式
String jsonString = "{message:\"success\",data:[{\"id\":\"1\",\"name\":\"小明\",\"sex\":\"男\"},{\"id\":\"2\",\"name\":\"小红\",\"sex\":\"女\"}]}";
JSONObject jo = JSONObject.parseObject(jsonString);
JSONArray jsonArray = jo.getJSONArray("data");
for(int i = 0; i < jsonArray.size(); i++){
System.out.println(jsonArray.getJSONObject(i).getString("id"));
System.out.println(jsonArray.getJSONObject(i).getString("name"));
System.out.println(jsonArray.getJSONObject(i).getString("sex"));
}
小结
通常会和实体一起使用json的相互转化,但是这次项目是用到了其它一些系统的数据,需求一直在变,实体不是很固定,所以json一直在比较灵活的转化中,仅作记录,方便查看