阿里JSONObject詳解



1.通過原生生成json數據格式。

JSONObject zhangsan = new JSONObject();
try {
//添加
zhangsan.put("name", "張三");
zhangsan.put("age", 18.4);
zhangsan.put("birthday", "1900-20-03");
zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
zhangsan.put("null", null);
zhangsan.put("house", false);
System.out.println(zhangsan.toString());
} catch (JSONException e) {
e.printStackTrace();
}

 

2.通過hashMap數據結構生成

HashMap<String, Object> zhangsan = new HashMap<>();

zhangsan.put("name", "張三");
zhangsan.put("age", 18.4);
zhangsan.put("birthday", "1900-20-03");
zhangsan.put("majar", new String[] {"哈哈","嘿嘿"});
zhangsan.put("null", null);
zhangsan.put("house", false);
System.out.println(new JSONObject(zhangsan).toString());

 

3.通過實體生成

Student student = new Student();
student.setId(1);
student.setAge("20");
student.setName("張三");
//生成json格式
System.out.println(JSON.toJSON(student));
//對象轉成string
String stuString = JSONObject.toJSONString(student);

 

4.JSON字符串轉換成JSON對象

String studentString = "{\"id\":1,\"age\":2,\"name\":\"zhang\"}";

//JSON字符串轉換成JSON對象
JSONObject jsonObject1 = JSONObject.parseObject(stuString);

System.out.println(jsonObject1);

 


5.list對象轉listJson

ArrayList<Student> studentLsit = new ArrayList<>();
Student student1 = new Student();
student1.setId(1);
student1.setAge("20");
student1.setName("asdasdasd");

studentLsit.add(student1);

Student student2 = new Student();
student2.setId(2);
student2.setAge("20");
student2.setName("aaaa:;aaa");

studentLsit.add(student2);

//list轉json字符串
String string = JSON.toJSON(studentLsit).toString();
System.out.println(string);

//json字符串轉listJson格式
JSONArray jsonArray = JSONObject.parseArray(string);

System.out.println(jsonArray);

 

參考:

https://blog.csdn.net/u012448904/article/details/84292821


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM