JSON key value pair serialization and deserialization resolution

  • 2021-07-15 03:40:23
  • OfStack

What is 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 Object Representation", it is a lightweight data exchange format, we can easily read and write it, and it is easy to be converted and generated by computer, it is completely independent of language.

For example, the obtained json string has the following fragments:


 " language " : { 
 " q " :  " Q " , 
 " a " :  " A "  
}

How do you quickly convert this string into a usable object?

Sample code:


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;
  }
}

The above code can be solved.

So conversely, how do you deserialize objects?

Sample code:


 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);

Related articles: