欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-09-08 14:59:20
什么是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键值对序列化和反序列化解析,希望对大家有所帮助