Home > Java > javaTutorial > Detailed example of how to convert Json into Java objects

Detailed example of how to convert Json into Java objects

黄舟
Release: 2017-08-10 09:22:35
Original
1533 people have browsed it

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>
Copy after login

Json string converted into List object:


JSONArray jsonArray = JSONArray.fromObject(jsonString);

List<Config> list = (List) JSONArray.toCollection(jsonArray,
          Class.class);
Copy after login

Json string converted into Object object


JSONObject jsonObject = JSONObject.fromObject(jsonString);
Object object = (Object) JSONObject.toBean(jsonObject, Object.class);
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template