Using Json-lib to convert between Java and JSON

Source: Internet
Author: User
Tags object object

1. Json-lib is a Java class library that provides the ability to convert Java objects, including beans, maps, collections, Java Arrays and XML, to JSON, or reverse-transform.

2. Json-lib Home: http://json-lib.sourceforge.net/

3. Execution Environment

The following class library support is required

    • Jakarta Commons-lang 2.5
    • Jakarta commons-beanutils 1.8.0
    • Jakarta commons-collections 3.2.1
    • Jakarta commons-logging 1.1.1
    • Ezmorph 1.0.6

4. Feature examples

The code example is given here through the junit-case example

Package Com.mai.json;

Import static org.junit.Assert.assertEquals;

Import java.util.ArrayList;
Import Java.util.Date;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.Map;
Import Net.sf.ezmorph.Morpher;
Import Net.sf.ezmorph.MorpherRegistry;
Import Net.sf.ezmorph.bean.BeanMorpher;
Import Net.sf.json.JSONArray;
Import Net.sf.json.JSONObject;
Import Net.sf.json.util.JSONUtils;

Import Org.apache.commons.beanutils.PropertyUtils;
Import Org.junit.Test;

public class Jsonlibtest {

/*
* Common Type, List, collection, etc. are analyzed with Jsonarray
*
* Map, custom type is resolved with Jsonobject
* Map can be understood as an object in which the Key/value is a property/attribute value that can be understood as an object
* That is {key1:value1,key2,value2 ...}
*
* 1.JSONObject is a name:values collection, obtained by its get (key) method is the corresponding value portion of the key (string)
* Through its getjsonobject (key) can be taken to a jsonobject,--> converted into a map,
* Through its getjsonarray (key) can be taken to a jsonarray,
*
*
*/

General arrays converted to JSON
@Test
public void Testarraytojson () {
boolean[] Boolarray = new Boolean[]{true,false,true};
Jsonarray Jsonarray = Jsonarray.fromobject (Boolarray);
System.out.println (Jsonarray);
Prints [true,false,true]
}


Collection objects into JSON
@Test
public void Testlisttojson () {
List List = new ArrayList ();
List.add ("first");
List.add ("second");
Jsonarray Jsonarray = jsonarray.fromobject (list);
System.out.println (Jsonarray);
Prints ["First", "second"]
}


The string JSON is converted to JSON, as the case may be with Jsonarray or jsonobject
@Test
public void Testjsonstrtojson () {
Jsonarray Jsonarray = Jsonarray.fromobject ("[' json ', ' is ', ' easy ']");
System.out.println (Jsonarray);
Prints ["JSON", "is", "easy"]
}


The map is converted to JSON, using Jsonobject
@Test
public void Testmaptojson () {
Map map = new HashMap ();
Map.put ("name", "JSON");
Map.put ("bool", boolean.true);
Map.put ("int", new Integer (1));
Map.put ("arr", New string[]{"A", "B"});
Map.put ("func", "function (i) {return this.arr[i];}");

Jsonobject jsonobject = jsonobject.fromobject (map);
System.out.println (Jsonobject);
}

Compound type Bean turns into JSON
@Test
public void Testbeadtojson () {
Mybean bean = new Mybean ();
Bean.setid ("001");
Bean.setname ("bank card");
Bean.setdate (New Date ());

List cardnum = new ArrayList ();
Cardnum.add ("abc");
Cardnum.add ("ICBC");
Cardnum.add ("CCB");
Cardnum.add (New person ("test"));

Bean.setcardnum (Cardnum);

Jsonobject jsonobject = Jsonobject.fromobject (bean);
System.out.println (Jsonobject);

}

Normal types of JSON are converted into objects
@Test
public void Testjsontoobject () throws exception{
String json = "{name=\" json\ ", Bool:true,int:1,double:2.2,func:function (a) {return A;},array:[1,2]}";
Jsonobject Jsonobject = Jsonobject.fromobject (JSON);
System.out.println (Jsonobject);
Object bean = Jsonobject.tobean (jsonobject);
Assertequals (Jsonobject.get ("name"), Propertyutils.getproperty (Bean, "name"));
Assertequals (Jsonobject.get ("bool"), Propertyutils.getproperty (Bean, "bool"));
Assertequals (Jsonobject.get ("int"), Propertyutils.getproperty (Bean, "int"));
Assertequals (Jsonobject.get ("Double"), Propertyutils.getproperty (Bean, "double"));
Assertequals (Jsonobject.get ("func"), Propertyutils.getproperty (Bean, "func"));
System.out.println (Propertyutils.getproperty (Bean, "name"));
System.out.println (Propertyutils.getproperty (Bean, "bool"));
System.out.println (Propertyutils.getproperty (Bean, "int"));
System.out.println (Propertyutils.getproperty (Bean, "double"));
System.out.println (Propertyutils.getproperty (Bean, "func"));
System.out.println (Propertyutils.getproperty (Bean, "array"));

List arrayList = (list) jsonarray.tocollection (Jsonobject.getjsonarray ("array"));
for (Object object:arraylist) {
System.out.println (object);
}

}


Parses the JSON into a composite type object that contains the list
@Test
public void Testjsontobeanhavalist () {
String json = "{list:[{name: ' test1 '},{name: ' test2 '}],map:{test1:{name: ' test1 '},test2:{name: ' Test2 '}}";
String json = "{list:[{name: ' test1 '},{name: ' Test2 '}]}";
Map Classmap = new HashMap ();
Classmap.put ("list", Person.class);
Mybeanwithperson Diybean = (Mybeanwithperson) Jsonobject.tobean (Jsonobject.fromobject (JSON), MyBeanWithPerson.class , Classmap);
System.out.println (Diybean);

List List = Diybean.getlist ();
for (Object o:list) {
if (o instanceof person) {
Person P = (person) o;
System.out.println (P.getname ());
}
}
}


Parses the JSON into a composite type object that contains the map
@Test
public void Testjsontobeanhavamap () {
Think of map as an object
String json = "{list:[{name: ' test1 '},{name: ' test2 '}],map:{testone:{name: ' test1 '},testtwo:{name: ' Test2 '}}";
Map Classmap = new HashMap ();
Classmap.put ("list", Person.class);
Classmap.put ("Map", Map.class);
Use the hint to parse the JSON directly into the specified custom object, where list is fully parsed and map is not fully parsed
Mybeanwithperson Diybean = (Mybeanwithperson) Jsonobject.tobean (Jsonobject.fromobject (JSON), MyBeanWithPerson.class , Classmap);
System.out.println (Diybean);

System.out.println ("Do the list release");
list<person> list = Diybean.getlist ();
for (person O:list) {
Person P = (person) o;
System.out.println (P.getname ());
}

System.out.println ("Do the map release");

To register the converter in the Registrar, you need to use the class in the Ezmorph package
Morpherregistry morpherregistry = Jsonutils.getmorpherregistry ();
Morpher dynamorpher = new Beanmorpher (Person.class, morpherregistry);
Morpherregistry.registermorpher (Dynamorpher);


Map map = Diybean.getmap ();
/* There is no type hint for the map here, so by default, the object is stored as Net.sf.ezmorph.bean.MorphDynaBean type */
SYSTEM.OUT.PRINTLN (map); /* Output: {[email protected][
{Name=test1}
], [email protected][
{Name=test2}
]}      */
list<person> output = new ArrayList ();
for (Iterator i = map.values (). Iterator (); I.hasnext ();) {
Using the Registrar to transform the specified Dynabean object
Output.add (person) morpherregistry.morph (Person.class, I.next ()));
}

for (person P:output) {
System.out.println (P.getname ()); /* Output: Test1
TEST2 * *
}

}



}

5. The resources required for the above example are provided below, including the jar package and code

/files/mailingfeng/json-lib/json-lib jar Packages and Java classes required for use cases. rar

Using Json-lib to convert between Java and JSON

Related Article

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.