当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JSON键值对序列化和反序列化解析

JSON键值对序列化和反序列化解析

2019年03月28日  | 移动技术网IT编程  | 我要评论
什么是json? json (javascript object notation) is a lightweight data-interchange format

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

“language”: { 
“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键值对序列化和反序列化解析,希望对大家有所帮助

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网