Conversion between Java objects and collections and Json strings.

Source: Internet
Author: User

Conversion between Java objects and collections and Json strings.

To sum up, use the Json jar package to convert Java objects and collections to Json strings:

1. created User class:

package com.ghj.packageofdomain;public class User {private int id;private String name;private String gender;public User() {}public User(int id, String name, String gender) {this.id = id;this.name = name;this.gender = gender;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}@Overridepublic String toString() {return "id=" + id + ",name=" + name + ",gender=" + gender;}}
2. Conversion between Java objects and collections and Json strings:
I. Conversion between Java objects and Json strings:

Package com. ghj. packageoftest; import net. sf. json. JSONObject; import com. ghj. packageofdomain. user; public class Test {public static void main (String [] args) {System. out. println (objectToJsonString (); jsonStringToObject (objectToJsonString ();}/*** convert a Java object to a Json String ** @ author */static String objectToJsonString () {JSONObject jsonObject = JSONObject. fromObject (new User (1, "James", "male"); return jsonObject. toString ();}/*** converts a Json String to a Java object ** @ author Gao huanjie */static void jsonStringToObject (String jsonString) {JSONObject jsonObject = JSONObject. fromObject (jsonString); User user User = (User) JSONObject. toBean (jsonObject, User. class); System. out. println (user );}}
Ii. Conversion between a Java set and a Json string:
Package com. ghj. packageoftest; import java. util. arrayList; import java. util. list; import net. sf. json. JSONArray; import com. ghj. packageofdomain. user; public class Test {public static void main (String [] args) {System. out. println (collectionToJsonString (); jsonStringToCollection (collectionToJsonString ();}/*** converts a Java Collection to a Json String ** @ author */static String collectionToJsonString () {List <User> userList = new ArrayList <User> (); userList. add (new User (1, "Michael", "male"); userList. add (new User (2, "", ""); userList. add (new User (3, "Wang Wu", "male"); JSONArray jsonArray = JSONArray. fromObject (userList); return jsonArray. toString ();}/*** converts a Json String to a Java Collection ** @ author Gao huanjie */static void jsonStringToCollection (String jsonString) {JSONArray jsonArray = JSONArray. fromObject (jsonString); @ SuppressWarnings ("unchecked") List <User> userList = (List <User>) JSONArray. toCollection (jsonArray, User. class); for (User user: userList) {System. err. println (user );}}}
Note:

1. In the preceding User class, there are not only constructors with parameters but also constructors without parameters. Some may ask why are there constructors with or without parameters? Heheh: To construct a User instance, a constructor with parameters is added. However, only the constructor without parameters must be added because of this constructor. Otherwise, the following exception occurs:

If it is not too complicated to construct a User instance, you can remove the two constructors. In fact, in this case, the non-argument constructor still exists, in a word, to convert a Json string to a Java instance or set, the constructor of the relevant class must have no parameters.

2. The conversion between Java objects and collections and Json requires the implementation of corresponding jar packages. These jar packages can be obtained in the Demo.

Download Demo at 0]


How does a java json-lib package convert a json string to a Bean object containing a complex set of types?

When using JSONObject. toBean, you need to pass in the list element type as a parameter.
The Code is as follows:
Map <String, Class> classMap = new HashMap <String, Class> ();
ClassMap. put ("list", B. class );
A j = (A) JSONObject. toBean (json, A. class, classMap );

In java, strings in json format are converted into objects.

To run a program, the JSON-lib package must be introduced. The JSON-lib package depends on the following JAR package:
1. commons-lang.jar
2. commons-beanutils.jar
3. commons-collections.jar
4. commons-logging.jar
5. ezmorph. jar
6. json-lib-2.2.2-jdk15.jar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.