The communication carrier between different programs, using json is a more convenient format, of course, the advantages of this format can be found at night, if speaking of the disadvantages, it may be all string transmission, the efficiency is not so high, but for general development programs, especially for Internet programs, more than enough.
gson library, maven's warehouse[ download ].
One of the creation modes of gson library is new gson, which is the default mode. In addition, there is a way of personalized configuration, gsonBuilder.
1. Convert JSON string to common type: int double String boolean
public static void testfromJson() { Gson gson = new Gson(); int number1 = gson.fromJson("999", int.class); double number2 = gson.fromJson("99.99", double.class); boolean number3 = gson.fromJson("true", boolean.class); String str = gson.fromJson("helloworld", String.class); numberSpecial number = gson.fromJson("{\"i\":1,\"j\":2.2,\"Address\":\"test\",\"flag\":true}", numberSpecial.class); }
2.POJO class converted to json
public static void testObjectToJson() { Gson gson = new Gson(); numberSpecial number = new numberSpecial(1,2.2,"test",true); String result = gson.toJson(number); System.out.println(result); numberSpecial number2 = gson.fromJson(result, numberSpecial.class); System.out.println(number2.i+" "+number2.j+" "+number2.str+" "+number.flag); }
3. String in JSON format, converted to array
public static void testArrayFromJson() { Gson gson = new Gson(); String jsonArray = "[\"USD\",\"CNY\",\"GBP\"]"; String [] strings = gson.fromJson(jsonArray, String[].class); for(int i=0; i< strings.length; i++) { System.out.println(strings[i]); } }
4. Convert list and map collection objects to json format strings.
public static void toListJSON() { List<numberSpecial> list = new ArrayList<>(); Map<String,numberSpecial> map = new HashMap<>(); numberSpecial number = new numberSpecial(3,3.3,"List",true); list.add(number); map.put("test1", number); numberSpecial number2 = new numberSpecial(3,3.3,"List",true); number2.i=4; list.add(number2); map.put("test2", number2); Gson gson = new Gson(); System.out.println("List json" + gson.toJson(list)); System.out.println("map json" + gson.toJson(map)); }
5. Convert string in json format to list and map collection objects.
public static void fromListJSON() { String jsonStr = "[{\"i\":3,\"j\":3.3,\"Address\":\"List\",\"flag\":true},{\"i\":4,\"j\":3.3,\"Address\":\"List\",\"flag\":true}]"; Gson gson = new Gson(); List<numberSpecial> list = gson.fromJson(jsonStr, new TypeToken<ArrayList<numberSpecial>>(){}.getType()); for(int i=0; i< list.size(); i++) { numberSpecial number2 = list.get(i); System.out.println(number2.i+" "+number2.j+" "+number2.str+" "+number2.flag); } }