JSON鍵值對序列化和反序列化解析
什么是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對象表示方法】,它是一個輕量級的數據交換格式,我們可以很簡單的來讀取和寫它,并且它很容易被計算機轉化和生成,它是完全獨立于語言的。
例如獲取到的json串有如下片段:
“l(fā)anguage”: { “q”: “Q”, “a”: “A” }
要如何將該字符串快速轉化成一個可以使用的對象呢?
示例代碼:
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; } }
以上代碼可以解決。
那么反過來,如何將對象反序列化呢?
示例代碼:
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鍵值對序列化和反序列化解析,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
相關文章
JavaScript最全公共方法匯總并解析(前端開發(fā)收藏必備)
JavaScript掌握各種常用的公共方法更是提升開發(fā)效率和代碼質量的關鍵,無論你是初學者還是資深開發(fā)者,了解并熟練運用這些方法都能讓你的代碼更加簡潔、高效,本篇博客將為你詳細匯總并解析最全的JavaScript公共方法,涵蓋數組、對象、字符串、日期等各個方面的常用技巧2024-06-06