Java uses Jsonobject instance _java

Source: Internet
Author: User

First, the introduction of JAR package
Use Jsonobject must refer to Json-lib.jar, and it also relies on other packages
Common-lang.jar
Common-beanuitls.jar
Common-collections.jar
Common-logging.jar
Ezmorph.jar
Second, the use of Jsonobject objects
The Json-lib package is a Java object, XML, and JSON-converted package.
1. Convert Java objects to JSON strings

Copy Code code as follows:

Person P1=new person ();
P1.setname ("Liu Dajiang");
P1.setage (26);
String Jsonstr=jsonobject.fromobject (p1). toString ();

2. Convert a Java collection into a JSON string
Copy Code code as follows:

Person P1=new person ();p 1.setName ("A1");p 1.setAge (26);
Person P2=new person ();p 2.setName ("A2");p 2.setAge (23);

List personlist=new arraylist<person> ();
Personlist.add (p1);
Personlist.add (p2);

Map personmap=new hashmap<string, person> ();
Personmap.put ("P1", p1);
Personmap.put ("P2", p2);

[{' Age ': ', ' name ': ' A1 '},{' age ': #, ' name ': ' A2 '}]
Jsonarray.fromobject (personlist). toString ();
Jsonserializer.tojson (Personlist)

[{' P2 ': {' name ': ' A2 ', ' Age ':}, ' P1 ': {' name ': ' A1 ', ' Age ': 26}}]
Jsonarray.fromobject (Personmap). toString ();
Jsonserializer.tojson (Personmap)

3. Convert a JSON string into a dynamic Java object

Copy Code code as follows:

String jsonstr= "[{\ name\": \ "a2\", \ "age\": 23},{\ "name\": \ "a1\", \ "age\": 26}] ";
Jsonarray Ja=jsonarray.fromobject (JSONSTR);

for (int i=0;i<ja.size (); i++) {
Jsonobject jo= Ja.getjsonobject (i); Convert to Jsonobject Object
System.out.println (Jo.get ("name"));

Person p= (person) Jsonobject.tobean (jo,person.class); Convert into JavaBean
System.out.println (P.getname ());

}

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.