Reversal of JSON strings and java objects [json-lib]
During the development process, you often need to exchange data with other systems. The formats of data exchange include XML, JSON, etc. JSON is a lightweight data format that is more efficient than xml. XML requires a lot of tags, which undoubtedly occupies network traffic. JSON does a good job in this regard. Let’s take a look at the format of JSON.
JSON can have two formats, one is object format, and the other is array object.
{"name":"JSON","address":"Xicheng District, Beijing","age":25}//JSON's object format string [{"name":"JSON","address":"Xicheng District, Beijing","age":25}]//Data object formatFrom the above two formats, we can see that the only difference between the object format and the array object format is that [] is added to the object format. Then look at the specific structure. It can be seen that they both appear in the form of key-value pairs, separated by commas (,) in the English state.
This format is also very popular when data transmission is carried out in the front-end and back-end. The back-end returns a string in json format. The front-end uses the JSON.parse() method in js to parse the JSON string into a json object, and then traversal for the front-end to use.
Let’s get to the topic and introduce the mutual conversion between JSON and java objects in JAVA.
To realize the mutual transfer between JSON and java objects, you need to use a third-party jar package. The json-lib package is used here. The download address is: https://sourceforge.net/projects/json-lib/. json-lib requires the support of five packages: commons-beanutils-1.8.0.jar, commons-collections-3.2.1.jar, commons-lang-2.5.jar, commons-logging-1.1.jar, and ezmorph-1.0.6.jar. You can download it from the Internet by yourself. The download address will no longer be posted here.
json-lib provides several classes that can complete this function, such as JSONObject, JSONArray. From the name of the class, we can see that the JSONObject transformed should be in object format, while the JSONArray transformed should be array objects (i.e., with the form []).
1. The mutual transfer of Java ordinary objects and json strings
java object--》》 string
A normal java object refers to a java bean in java, that is, an entity class, such as
package com.cn.study.day3;public class Student { //Name private String name; //Age private String age; //Address private String address; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + ", address=" + address + "]"; } }Above is a normal java entity class of mine, see how json-lib converts it into a string form,
public static void convertObject() { Student stu=new Student(); stu.setName("JSON"); stu.setAge("23"); stu.setAddress("Beijing Xicheng District"); //1. Use JSONObject JSONObject json = JSONObject.fromObject(stu); //2. Use JSONArray JSONArray array=JSONArray.fromObject(stu); String strJson=json.toString(); String strArray=array.toString(); System.out.println("strJson:"+strJson); System.out.println("strArray:"+strArray); }I defined a Student's entity class, and then converted it into JSON strings using JSONObject and JSONArray respectively. Let's see the printed result below.
strJson:{"address":"Xicheng District, Beijing","age":"23","name":"JSON"}strArray:[{"address":"Xicheng District, Beijing","age":"23","name":"JSON"}]From the results, we can see that both methods can convert java objects into JSON strings, but the converted structure is different.
JSON string--》》java object
The above explains how to convert java objects into JSON strings. Let’s see how to convert JSON string format into java objects.
First, you need to define two strings in different formats, you need to use/escape double quotes.
public static void jsonStrToJava(){ //Define two strings in different formats String objectStr="{/"name/":/"JSON/",/"age/":/"24/",/"address/":/"Xicheng District, Beijing/"}"; String arrayStr="[{/"name/":/"JSON/",/"age/":/"24/",/"address/":/"Xicheng District, Beijing/"}]"; //1. Use JSONObject JSONObject jsonObject=JSONObject.fromObject(objectStr); Student stu=(Student)JSONObject.toBean(jsonObject, Student.class); //2. Use JSONArray JSONArray jsonArray=JSONArray.fromObject(arrayStr); //Get the first element of jsonArray Object o=jsonArray.get(0); JSONObject jsonObject2=JSONObject.fromObject(o); Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class); System.out.println("stu:"+stu); System.out.println("stu2:"+stu2); }The print result is:
stu:Student [name=JSON, age=24, address=Xicheng District, Beijing]stu2:Student [name=JSON, age=24, address=Xicheng District, Beijing]
As can be seen from the above code, using JSONObject can easily convert JSON format strings into java objects, but using JSONArray is not that easy, because it has the "[]" symbol, so after we get the JSONArray object, we take the first element, which is the deformation of the student we need, and then use JSONObject to easily obtain it.
2. Transfer of list and json strings
list--》》json string
public static void listToJSON(){ Student stu=new Student(); stu.setName("JSON"); stu.setAge("23"); stu.setAddress("Beijing Haidian District"); List<Student> lists=new ArrayList<Student>(); lists.add(stu); //1. Use JSONObject //JSONObject listObject=JSONObject.fromObject(lists); //2. Use JSONArray JSONArray listArray=JSONArray.fromObject(lists); //System.out.println("listObject:"+listObject.toString()); System.out.println("listArray:"+listArray.toString()); }I've used JSONObject to bet out. Let's look at the results before the comment.
Exception in thread "main" net.sf.json.JSONException: 'object' is an array. Use JSONArray instead
Tell me that there is an exception. By checking the source code, I found that when using the fromObject method, I will first judge the parameter type. Here I tell us that the passed parameter is an array type because the ArrayList is used. Let’s look at the result after the comment.
listArray:[{"address":"Haidian District, Beijing","age":"23","name":"JSON"}] This result is normal.
json string--》》list
From the above example, we can see that the list object can only be converted into the format of array object. So let’s look at the conversion from the string to the list below.
public static void jsonToList(){ String arrayStr="[{/"name/":/"JSON/",/"age/":/"24/",/"address/":/"Beijing Xicheng District/"}]"; //Convert to list List<Student> list2=(List<Student>)JSONArray.toList(JSONArray.fromObject(arrayStr), Student.class); for (Student stu : list2) { System.out.println(stu); } //Convert to array Student[] ss =(Student[])JSONArray.toArray(JSONArray.fromObject(arrayStr),Student.class); for (Student student : ss) { System.out.println(student); } }Print the result,
Student [name=JSON, age=24, address=Xicheng District, Beijing]Student [name=JSON, age=24, address=Xicheng District, Beijing]
Since the format of the string is in the format with "[]", the JSONArray object is selected here, which has toArray and toList methods for use. The former is converted into an array in java, or into a list in java. Since there is an entity class here to correspond, the type of the generic (Student.class) is specified when using it, so the converted object can be obtained.
3. The map and json string conversion
map--》》json string
public static void mapToJSON(){ Student stu=new Student(); stu.setName("JSON"); stu.setAge("23"); stu.setAddress("Shanghai, China"); Map<String,Stu> map=new HashMap<String,Student>(); map.put("first", stu); //1. JSONObject JSONObject mapObject=JSONObject.fromObject(map); System.out.println("mapObject"+mapObject.toString()); //2. JSONArray JSONArray mapArray=JSONArray.fromObject(map); System.out.println("mapArray:"+mapArray.toString()); }Print the result,
mapObject{"first":{"address":"Shanghai,"age":"23","name":"JSON"}}mapArray:[{"first":{"address":"Shanghai,"age":"23","name":"JSON"}}]Two forms are printed above.
json string--》》map
JSON strings cannot be directly converted into map objects. In order to obtain the value corresponding to the keys in maps, other methods are required.
public static void jsonToMap(){ String strObject="{/"first/":{/"address/":/"Shanghai, China/",/"age/":/"23/",/"name/":/"JSON/"}}"; //JSONObject JSONObject jsonObject=JSONObject.fromObject(strObject); Map map=new HashMap(); map.put("first", Student.class); //The toBean method is used, and three parameters are required for MyBean my=(MyBean)JSONObject.toBean(jsonObject, MyBean.class, map); System.out.println(my.getFirst()); }Print the result,
Student [name=JSON, age=23, address=Shanghai, China]
Below is the code of MyBean.
package com.cn.study.day4;import java.util.Map;import com.cn.study.day3.Student;public class MyBean { private Student first; public Student getFirst() { return first; } public void setFirst(Student first) { this.first = first; } } Using the toBean() method, three parameters are passed in, the first is the JSONObject object, the second is MyBean.class, and the third is a Map object. Through MyBean, we can know that there must be a first attribute in this class, and its type is Student, which corresponds to the key and value types in the map, that is, the type of the value corresponding to the first key type.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.