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串有如下片段:

rush:js;"> “language”: { “q”: “Q”,“a”: “A” }

要如何将该字符串快速转化成一个可以使用的对象呢?

示例代码

rush:js;"> JSONObject language = obj.optJSONObject("language"); if(language !=null ){ try { HashMap nickname = new Gson().fromJson(language.toString(),new Typetoken>(){}.getType()); }catch (Exception e){ HashMap nickname = null; } }

以上代码可以解决

那么反过来,如何将对象反序列化呢?

示例代码

rush:js;"> Map map = new HashMap(); map.put("int",123); map.put("long",1234567890123456789L); map.put("double",1234.5678D); map.put("float",1.2345F); Type mapType = new Typetoken>() {}.getType(); Gson gson = new GsonBuilder().registerTypeAdapter(Number.class,new NumberTypeAdapter()).create(); String json = gson.toJson(map,mapType);

以上所述是小编给大家介绍的JSON键值对序列化和反序列化解析。编程之家 jb51.cc 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...