How to use JSON in Java

Source: Internet
Author: User

JSON plays a big role in data transfer, and the following is how JSON is used in Java.

Article reference: http://www.codes51.com/article/detail_99574.html

JSON string Example

[{"id": 1, "name": "Name1", "Password": "Password1", "remark": "Remark1"},{"id": 2, "name": "Name2", "Password": " Password2 "," remark ":" REMARK2 "},{" id ": 3," name ":" Name3 "," Password ":" Password3 "," remark ":" Remark3 "}]

Mainly divided into the following types:

1. Directly build the JSON string, the main code;

2. JSON strings, Java objects;

3. JSON string/json object, Java object;

4. JSON string list<?>;

5. JSON string, array of objects.

The procedure is as follows:

Testjson.java

Java Code Collection Code

Import java.util.*;

Import net.sf.json.*;

Import Com.hs.sig.ui.sgms.vo.User;

public class Testjson {

/**

* Initialize userlist size

*/

public static final int userlistsize = 3;

/**

* Build JSON strings directly

* @return

*/

Public String tojsonstring () {

Initializing the User object

User user = null;

List<user> userlist = this.inituserlist (userlistsize);

Building a JSON string

StringBuffer json = new StringBuffer ();

Json.append ("[");

for (int i = 0; i < userlist.size (); i++) {

user = Userlist.get (i);

Json.append ("{");

Json.append ("\" id\ ": \" "). Append (User.getid ()). Append (" \ ",");

Json.append ("\" name\ ": \" "). Append (User.getname ()). Append (" \ ",");

Json.append ("\" password\ ": \" "). Append (User.getpassword ()). Append (" \ ",");

Json.append ("\" Remark\ ": \" "). Append (User.getremark ()). Append ('" ');

Json.append ("},");

}

Json.deletecharat (Json.lastindexof (","));

Json.append ("]");

System.out.println ("Direct build JSON string result:" + json.tostring ());

return json.tostring ();

}

/**

* JSON strings, Java objects

* @return

*/

Public String Jsontoobject () {

StringBuffer info = new StringBuffer ();

if (This.isarray (this.tojsonstring ())) {

Jsonarray Jsonarray = Jsonarray.fromobject (this.tojsonstring ());

Jsonconfig jsonconfig = new Jsonconfig ();

Jsonconfig.setarraymode (jsonconfig.mode_list);

Jsonconfig.setrootclass (User.class);

List<user> userlist = (list<user>) Jsonserializer.tojava (Jsonarray, jsonconfig);

User user = null;

for (int i = 0; i < userlist.size (); i++) {

user = Userlist.get (i);

Info.append ("User" + (i + 1) + ". Id=" + User.getid ());

Info.append (", user" + (i + 1) + ". Name=" + user.getname ());

Info.append (", user" + (i + 1) + ". Password=" + User.getpassword ());

Info.append (", user" + (i + 1) + ". remark=" + User.getremark ());

Info.append ("\ n");

}

SYSTEM.OUT.PRINTLN ("JSON Strings, Java objects:" + info.tostring ());

}

return info.tostring ();

}

/**

* Java object, JSON string/json object

* @return

*/

Public String Objecttojson () {

Initializes a user object

User user = null;

List<user> userlist = this.inituserlist (userlistsize);

user = Userlist.get (0);

To convert the configuration of a user object

Jsonconfig jsonconfig = new Jsonconfig ();

Filter properties that do not require conversion in an object

Jsonconfig.setexcludes (new string[]{"id"});

Convert object user to JSON string

Jsonarray Jsonarray = jsonarray.fromobject (user, jsonconfig);

Jsonarray = jsonarray.fromobject (user);

Convert to JSON object

Jsonobject Jsonobject = jsonobject.fromobject (user, jsonconfig);

Jsonobject = jsonobject.fromobject (user);

return jsonarray.tostring ();

}

/**

* list<user> JSON string

* @return

*/

Public String Listtojson () {

List<user> userlist = this.inituserlist (userlistsize);

List converted to JSON string

Jsonarray Jsonarray = Jsonarray.fromobject (userlist);

System.out.println ("list<user>, JSON string:" + jsonarray.tostring ());

return jsonarray.tostring ();

}

/**

* JSON string with object array

* @return

*/

Public String Arraytojson () {

List<user> userlist = this.inituserlist (userlistsize);

user[] Userarray = new user[userlist.size ()];

for (int i = 0; i < userlist.size (); i++) {

Userarray[i] = Userlist.get (i);

}

The user array is converted to a JSON string

Jsonarray Jsonarray = Jsonarray.fromobject (Userarray);

System.out.println ("Object array, JSON string:" + jsonarray.tostring ());

return jsonarray.tostring ();

}

/**

* Initialize User

* @param the size of the Userlistsize list

* @return

*/

Private list<user> inituserlist (int userlistsize) {

User user = null;

list<user> userlist = new arraylist<user> ();

for (int i = 0; i < userlistsize; i++) {

user = new User ();

User.setid (i + 1);

User.setname ("name" + (i + 1));

User.setpassword ("Password" + (i + 1));

User.setremark ("Remark" + (i + 1));

Userlist.add (user);

}

return userlist;

}

/**

* Determine if the JSON string starts with "[", is considered jsonarray, otherwise it is identified as Jsonobject

* @param str

* @return

*/

Private Boolean IsArray (String str) {

return Str.startswith ("[")? True:false;

}

public static void Main (string[] args) {

Testjson Testjson = new Testjson ();

SYSTEM.OUT.PRINTLN ("Directly build JSON string:" + testjson.tojsonstring ());

SYSTEM.OUT.PRINTLN ("JSON Strings, Java objects:" + testjson.jsontoobject ());

System.out.println ("Java object, JSON string:" + Testjson.objecttojson ());

System.out.println ("list<user>, JSON string:" + Testjson.listtojson ());

System.out.println ("Object array, JSON string:" + Testjson.arraytojson ());

}

}

User.java


Java code

public class User {

Private Integer ID;

private String name;

private String password;

Private String remark;

Public String GetName () {

return name;

}

public void SetName (String name) {

THIS.name = name;

}

Public String GetPassword () {

return password;

}

public void SetPassword (String password) {

This.password = password;

}

Public String Getremark () {

return remark;

}

public void Setremark (String remark) {

This.remark = remark;

}

Public Integer getId () {

return ID;

}

public void SetId (Integer id) {

This.id = ID;

}

}



Directly build the JSON string: [{"id": "1", "name": "Name1", "Password": "Password1", "remark": "Remark1"},{"id": "2", "Name": "Name2", " Password ":" Password2 "," remark ":" REMARK2 "},{" id ":" 3 "," Name ":" Name3 "," Password ":" Password3 "," remark ":" Remark3 "}]

JSON strings, Java objects: USER1.ID=1,USER1.NAME=NAME1,USER1.PASSWORD=PASSWORD1,USER1.REMARK=REMARK1

User2.id=2,user2.name=name2,user2.password=password2,user2.remark=remark2

User3.id=3,user3.name=name3,user3.password=password3,user3.remark=remark3

Java object, JSON string: [{"Name": "Name1", "Password": "Password1", "remark": "Remark1"}]

List<user>. JSON string: [{"id": 1, "name": "Name1", "Password": "Password1", "remark": "Remark1"},{"id": 2, "name": " Name2 "," Password ":" Password2 "," remark ":" REMARK2 "},{" id ": 3," name ":" Name3 "," Password ":" Password3 "," remark ":" Remark3 "}]

Array of objects, JSON string: [{"id": 1, "name": "Name1", "Password": "Password1", "remark": "Remark1"},{"id": 2, "name": "Name2", " Password ":" Password2 "," remark ":" REMARK2 "},{" id ": 3," name ":" Name3 "," Password ":" Password3 "," remark ":" Remark3 "}]

How to use JSON in Java

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.