Conversion of Java objects and collections to JSON

Source: Internet
Author: User

Summarize the conversion between the Java object and the collection and JSON:

1. Create the 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:
I, the conversion between Java objects and JSON:

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 Java object to JSON string *  * @author Gao Yingjie */static string objecttojsonstring () {Jsonobject jsonobject = Jsonobject.fromo Bject (New User (1, "Zhang San", "male"));    return jsonobject.tostring ();} /** * Convert JSON string to Java Object *  * @author Gao Yingjie */static void Jsonstringtoobject (String jsonstring) {Jsonobject Jsonobject = JS Onobject.fromobject (jsonstring); User user = (user) Jsonobject.tobean (jsonobject, User.class); SYSTEM.OUT.PRINTLN (user);}}
II, the conversion between the Java collection and JSON:




Conversion of Java objects and collections to JSON

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.