Introduction to JSON and Jsonobject generation JSON

Source: Internet
Author: User

I. INTRODUCTION of JSON

Json:javascript Object Notation (JavaScript object Notation)

XML-like: syntax for storing and exchanging information

Faster and easier to parse than XML

JSON syntax rules:

1. Data in name/value pairs

2, the data is separated by commas

3. Save the object with curly braces

4, square brackets to save the array

JSON value:

1, Number: integer or floating point

2. String: in double quotes

3. Logical value: True False

4. Array: in square brackets

5. Object: In curly braces

6, NULL

Second, using Jsonobject to generate JSON in Java

The required packages

Commons-httpclient-3.1.jar

Commons-lang-2.4.jar

Commons-logging-1.1.1.jar

Json-lib-2.4-jdk15.jar

Ezmorph-1.0.6.jar

Commons-collections-3.2.1.jar

1. The bean is converted to JSON

User U = new user ();
U.setage (22);
U.setusername ("HZUCMJ");
U.setenabled (TRUE);

Jsonobject json = jsonobject.fromobject (u);
System.out.println (Json.tostring ()); The result is: {"Enabled": True, "username": "HZUCMJ", "Age": 22}

2. List is converted to JSON

User U1 = new user ();
U1.setage (22);
U1.setusername ("HZUCMJ");
U1.setenabled (TRUE);

User U2 = new user ();
U2.setage (20);
U2.setusername ("CTF");
U2.setenabled (TRUE);

list<object> list = new arraylist<object> ();
List.add (U1);</p>
List.add (U2);</p>

Jsonarray json = jsonarray.fromobject (list);
System.out.println (Json.tostring ()); The result is: [{"Enabled": False, "username": "CTF", "Age": 20},{"Enabled": False, "username": "", "Age": 0}]

3. Map to JSON

hashmap<string, comparable> map = new hashmap<string, comparable> ();
Map.put ("name", "HZUCMJ");
Map.put ("Age", 22);
Jsonobject JSON = jsonobject.fromobject (map);
System.out.println (Json.tostring ()); The result is: {"name": "HZUCMJ", "Age": 22}

This article is reproduced in part: http://blog.csdn.net/ygzk123/article/details/8273293

Introduction to JSON and Jsonobject generation 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.