JSON和GSON操作json数据
1,JSON操作json
1 import net.sf.json.JSONArray; 2 import net.sf.json.JSONObject; 3 4 //json操作数据 5 public static String objToJson(User user) 6 { 7 JSONObject jsonObject = JSONObject.fromObject(user); 8 return jsonObject.toString(); 9 } 10 public static User jsonToObj(String str) 11 { 12 JSONObject jsonObject = JSONObject.fromObject(str); 13 User user = (User)jsonObject.toBean(jsonObject, User.class); 14 return user; 15 } 16 public static JSONArray strToJsonArray(List<User> users) 17 { 18 return JSONArray.fromObject(users); 19 } 20
2,GSON操作json
1 import com.google.gson.Gson; 2 3 //gson操作数据 4 public static String objToJson(User user) 5 { 6 Gson gson = new Gson(); 7 return gson.toJson(user); 8 } 9 public static User jsonToObj(String str) 10 { 11 Gson gson = new Gson(); 12 User user5 = (User)gson.fromJson(str, User.class); 13 return user5; 14 }