Operate JSON string objects using Java

Source: Internet
Author: User

1. If we need to implement a configuration management function, adding a field for each configuration item is both complex and not conducive to expansion. Therefore, we usually use a string to save the configuration item information, this section describes how to use JSON string parsing to achieve the purpose just described. Introduce the class library required by JSON:

Import org. JSON. jsonexception;
Import org. JSON. jsonobject;

2. Generate a JSON object (you can add different types of data ):

Jsonobject = new jsonobject ();
Jsonobject. Put ("A", 1); jsonobject. Put ("B", 1.1 );
Jsonobject. Put ("C", 1l );
Jsonobject. Put ("D", "test ");
Jsonobject. Put ("e", true );
System. Out. println (jsonobject );
// {"D": "test", "E": True, "B": 1.1, "C": 1, "A": 1}
 

3. parse a JSON object (different types of data can be parsed), getjsonobject (string Str ):

Jsonobject = getjsonobject ("{d: Test, E: True, B: 1.1, C: 1, A: 1 }");
System. Out. println (jsonobject );
// {"D": "test", "E": True, "B": 1.1, "C": 1, "A": 1}
System. Out. println (jsonobject. getint (""));
System. Out. println (jsonobject. getdouble ("B "));
System. Out. println (jsonobject. getlong ("C "));
System. Out. println (jsonobject. getstring ("D "));
System. Out. println (jsonobject. getboolean ("e "));

4,

Public static jsonobject getjsonobject (string Str ){
If (STR = NULL | Str. Trim (). Length () = 0 ){
Return NULL;
}
Jsonobject = NULL;
Try {
Jsonobject = new jsonobject (STR );
} Catch (jsonexception e ){
E. printstacktrace (system. Err );
}
Return jsonobject;
}

 

Pack: http://www.json.org/java/index.html

 

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.