This article mainly introduces relevant information on the detailed explanation of examples of converting Json into Java objects. In the case of front-end and back-end data interaction, we often encounter the mutual conversion of Json strings and Java objects for convenient operations. Friends in need can refer to it
Detailed explanation of examples of converting Json into Java objects
Problem: When interacting with front-end and back-end data, we often encounter the problem of converting Json strings into Java objects. Some Java objects Also includes List objects, etc.
Solution:
Introduce the json-lib package, the Maven coordinates are as follows:
<dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.4</version> <classifier>jdk15</classifier> </dependency>
Json string converted into List object:
JSONArray jsonArray = JSONArray.fromObject(jsonString); List<Config> list = (List) JSONArray.toCollection(jsonArray, Class.class);
Json string converted into Object object
JSONObject jsonObject = JSONObject.fromObject(jsonString); Object object = (Object) JSONObject.toBean(jsonObject, Object.class);
Json string is converted into an Object object containing a List object
JSONObject jsonObject = JSONObject.fromObject(jsonString); Map<String, Class> listMap = new HashMap<String, Class>(); listMap.put("list", listObject.class); Object object = (Object) JSONObject.toBean(jsonObject, Object.class, listMap);
PS: The Object object may contain multiple objects, and the object may contain multiple List objects nested in each other.
You only need to assemble all the List object values into a Map object, and the corresponding key is the attribute name of the List object.
The above is the detailed content of Detailed example of how to convert Json into Java objects. For more information, please follow other related articles on the PHP Chinese website!