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

“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键值对序列化和反序列化解析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!