JSONObject用法詳解
JSONObject只是一種數(shù)據(jù)結(jié)構(gòu),可以理解為JSON格式的數(shù)據(jù)結(jié)構(gòu)(key-value結(jié)構(gòu)),可以使用put方法給json對象添加元素。JSONObject可以很方便的轉(zhuǎn)換成字符串,也可以很方便的把其他對象轉(zhuǎn)換成JSONObject對象。
pom:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
1.通過原生生成json數(shù)據(jù)格式。
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數(shù)據(jù)結(jié)構(gòu)生成
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));
//對象轉(zhuǎn)成string
String stuString = JSONObject.toJSONString(student);
4.JSON字符串轉(zhuǎn)換成JSON對象
String studentString = "{\"id\":1,\"age\":2,\"name\":\"zhang\"}";
//JSON字符串轉(zhuǎn)換成JSON對象
JSONObject jsonObject1 = JSONObject.parseObject(stuString);
System.out.println(jsonObject1);
5.list對象轉(zhuǎn)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轉(zhuǎn)json字符串
String string = JSON.toJSON(studentLsit).toString();
System.out.println(string);
//json字符串轉(zhuǎn)listJson格式
JSONArray jsonArray = JSONObject.parseArray(string);
System.out.println(jsonArray);
阿里的json很好用,還有一個谷歌Gson也不錯。有興趣的可以看一看
到此這篇關(guān)于JSONObject用法詳解的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
nodeType屬性返回被選節(jié)點的節(jié)點類型介紹
這篇文章主要介紹了nodeType屬性返回被選節(jié)點的節(jié)點類型。需要的朋友可以過來參考下,希望對大家有所幫助2013-11-11
getElementById().innerHTML與getElementById().value的區(qū)別
這篇文章主要介紹了getElementById().innerHTML與getElementById().value的區(qū)別,因為經(jīng)常有新手朋友問到,特整理一下,需要的朋友可以參考下2016-10-10
javascript數(shù)據(jù)代理與事件詳解分析
所謂數(shù)據(jù)代理(也叫數(shù)據(jù)劫持),指的是在訪問或者修改對象的某個屬性時,通過一段代碼攔截這個行為,進行額外的操作或者修改返回結(jié)果。比較典型的是 Object.defineProperty() 和 ES2015 中新增的 Proxy 對象2021-11-11

