JSON encoding and decoding using java
coding
From Java variables to JSON format encoding process is as follows:
public void testJson() {
JSONObject object = new JSONObject();
//string
object.put("string","string");
//int
object.put("int",2);
//boolean
object.put("boolean",true);
//array
List<Integer> integers = Arrays.asList(1,2,3);
object.put("list",integers);
//null
object.put("null",null);
System.out.println(object);
}
In the above example, first create a JSON object, and then successively adding string, integer, and Boolean array, and finally to print a string.
Output:
{"boolean":true,"string":"string","list":[1,2,3],"int":2}
decoding
Variable from Java objects to JSON decoding process is as follows:
Examples
public void testJson2() {
JSONObject object = JSONObject
.parseObject("{\"boolean\":true,\"string\":\"string\",\"list\":[1,2,3],\"int\":2}");
String s = object.getString("string");//string
System.out.println(s);
int i = object.getIntValue("int"); //int
System.out.println(i);
boolean b = object.getBooleanValue("boolean"); //boolean
System.out.println(b);
List<Integer> integers = JSON.parseArray(object.getJSONArray("list").toJSONString(),Integer.class); //list
integers.forEach(System.out::println);
System.out.println(object.getString("null")); //null
}
In the above example, the first constructed in a JSON-formatted string JSON object, then sequentially read a string, integer, Boolean, and array, respectively, the final print.
Print results are as follows:
string
2
true
1
2
3
null
JSON object string mutual conversion
method | effect |
---|---|
JSON.parseObject() | Parsing JSON object from a string |
JSON.parseArray() | From the array of string parsing JSON |
JSON.toJSONString(obj/array) | The JSON object into a string or array of JSON |