Json-lib Simple to use

Source: Internet
Author: User

Json-lib can convert A Java object to a JSON-formatted string or a Java object to a XML -formatted document, you can also convert a json string to a Java object or XML The string is converted into a Java object.

1. first go to the official download json-lib Toolkit (http://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/)

Json-lib relies on the following packages:

Let's start by introducing the use of Json-lib:

In the actual project, in order to code reusability, reduce code redundancy, often some methods are encapsulated, use the time to call directly, do not have to rewrite the same code every time.

Json-lib can handle a collection or a single object into a JSON string, for a collection or a single object json-lib take a different approach to separate processing:

1) When the parameter is a single object:

Convert a Parameter object to a Jsonobject object

Jsonobject jsonobject = Jsonobject.fromobject (pobject);

Get the JSON string by jsonobject 's toString () method

String jsonstring = jsonobject.tostring ();

2) When the parameter is a collection type

Convert a Parameter object to a jsonarray Object

Jsonarray Jsonarray = Jsonarray.fromobject (pobject);

Get the JSON string by Jsonarray's toString () method

String jsonstring = jsonarray.tostring ();

※json-lib when processing date formatting, be aware that if you want to format the output date, you need to implement the Jsonvalueprocessor interface manually to process the date. Two methods are declared in the Jsonvalueprocessor interface: Processarrayvalue (Object value, Jsonconfig jsonconfig) and Processobjectvalue (String key, Object Value,jsonconfig jsonconfig), as the name implies, is processed for array collections and individual objects, respectively.

Here is my implementation:

/**

Implement Jsonvalueprocessor interface

*/

Public class Datejsonvalueprocessor implements jsonvalueprocessor{

Private String Format = "Yyyy-mm-dd HH:mm:ss" ;

Public Datejsonvalueprocessor (String format) {

this. format = format;

}

/**

*

Processing for arrays

*/

Public Object Processarrayvalue (object value, Jsonconfig jsonconfig) {

string[] obj = {};

if (Value instanceof java.util.date[]) {

SimpleDateFormat SF = new simpledateformat (format);

java.util.date[] dates = (java.util.date[]) value;

obj = new string[dates. Length];

for (int i = 0; i < dates. length; i++) {

Obj[i] = Sf.format (Dates[i]);

}

}

if (Value instanceof timestamp[]) {

SimpleDateFormat SF = new simpledateformat (format);

timestamp[] dates = (timestamp[]) value;

obj = new string[dates. Length];

for (int i = 0; i < dates. length; i++) {

Obj[i] = Sf.format (Dates[i]);

}

}

if (Value instanceof java.sql.date[]) {

SimpleDateFormat SF = new simpledateformat (format);

java.sql.date[] dates = (java.sql.date[]) value;

obj = new string[dates. Length];

for (int i = 0; i < dates. length; i++) {

Obj[i] = Sf.format (Dates[i]);

}

}

return obj;

}

/**

* Format a single object

*/

Public Object Processobjectvalue (String key, object value,

Jsonconfig jsonconfig) {

Determine if value is empty

if (Gsutils.isempty (value)) {

return "";

}

Determine the value type

if (Value instanceof Timestamp) {

String str = new simpledateformat (format). Format ((Timestamp) value);

return str;

} Else if (value instanceof java.util.Date) {

String str = new simpledateformat (format). Format ((java.util.Date) value);

return str;

} Else if (value instanceof java.sql.Date) {

String str = new simpledateformat (format). Format ((java.sql.Date) value);

return str;

}

return value.tostring ();

}

Public String GetFormat () {

return format;

}

Public void setformat (String format) {

this. format = format;

}

}

The implementation of the Jsonvalueprocessor interface, is not finished, because Json-lib do not know Ah, so to continue, now we need to use the jsonconfig class, by using this class, We can register our custom implementation on Json-lib with the following key code:

Jsonconfig cfg = New jsonconfig();

cfg.registerjsonvalueprocessor (java.sql.Timestamp. class ,  New datejsonvalueprocessor (pformatstring));

cfg.registerjsonvalueprocessor (java.util.Date. class ,  New datejsonvalueprocessor (pformatstring));

cfg.registerjsonvalueprocessor (java.sql.Date. class ,  New datejsonvalueprocessor (pformatstring));

At this point we have finally finished the task, but continue to see it, we need to pass the jsonconfig object into the fromobject , pay attention to the cfg

1) When the parameter is a single object:

Convert a Parameter object to a Jsonobject object

Jsonobject jsonobject = Jsonobject.fromobject (pobject,cfg);

Get the JSON string by jsonobject 's toString () method

String jsonstring = jsonobject.tostring ();

2) When the parameter is a collection type

Convert a Parameter object to a jsonarray Object

Jsonarray Jsonarray = Jsonarray.fromobject (pobject,cfg);

Get the JSON string by Jsonarray's toString () method

String jsonstring = jsonarray.tostring ();

...

About the json-lib function is very powerful, here is only work involving this part of the knowledge points, more functions please refer to the API, here is a brief introduction to some of the common methods of work:

Tobean (String jsonstring, Class Targetclass)--- to convert a JSON string into a target object, it is important to note that there must be an empty constructor in the target class.

ToString ()---Convert a java object to a json string

ToArray ()-- get the corresponding java array from the JSON string

ToArray ()--Convert list to Array

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.