您好,登錄后才能下訂單哦!
什么是JSON?
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language independent.
翻譯:Json【javascript對(duì)象表示方法】,它是一個(gè)輕量級(jí)的數(shù)據(jù)交換格式,我們可以很簡單的來讀取和寫它,并且它很容易被計(jì)算機(jī)轉(zhuǎn)化和生成,它是完全獨(dú)立于語言的。
例如獲取到的json串有如下片段:
“l(fā)anguage”: { “q”: “Q”, “a”: “A” }
要如何將該字符串快速轉(zhuǎn)化成一個(gè)可以使用的對(duì)象呢?
示例代碼:
JSONObject language = obj.optJSONObject("language"); if(language !=null ){ try { HashMap<String,String> nickname = new Gson().fromJson(language.toString() , new TypeToken<HashMap<String, String>>(){}.getType()); }catch (Exception e){ HashMap<String,String> nickname = null; } }
以上代碼可以解決。
那么反過來,如何將對(duì)象反序列化呢?
示例代碼:
Map<String, Number> map = new HashMap<String, Number>(); map.put("int", 123); map.put("long", 1234567890123456789L); map.put("double", 1234.5678D); map.put("float", 1.2345F); Type mapType = new TypeToken<Map<String, Number>>() {}.getType(); Gson gson = new GsonBuilder().registerTypeAdapter(Number.class , new NumberTypeAdapter()).create(); String json = gson.toJson(map, mapType);
以上所述是小編給大家介紹的JSON鍵值對(duì)序列化和反序列化解析,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)億速云網(wǎng)站的支持!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。