Transition between Java and JSON objects _java

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, into JSON, or reverse conversion.

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

3. Implementation environment

The following class library support is required

Commons-lang 2.5
Commons-beanutils 1.8.0
Commons-collections 3.2.1
Commons-logging 1.1.1
Ezmorph 1.0.6
4. Function Example

Here is a sample of the code through the Junit-case example

Copy Code code as follows:

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 and so on are all used Jsonarray analysis
*
* Map, custom type is resolved using Jsonobject
* You can interpret a map 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 set with its get (key) method to obtain the corresponding value portion of the key (string)
* Through its getjsonobject (key) can be taken to a jsonobject,--> converted to map,
* Through its getjsonarray (key) can be taken to a jsonarray,
*
*
*/

Convert a generic array into 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]
}


Convert collection object into JSON
@Test
public void Testlisttojson () {
List List = new ArrayList ();
List.add ("a");
List.add ("second");
Jsonarray Jsonarray = jsonarray.fromobject (list);
System.out.println (Jsonarray);
Prints ["A", "second"]
}


String JSON is converted to JSON, depending on whether the 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 the 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 to be turned 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 type of JSON converted to an object
@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 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 JSON into a composite type object, containing a 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 hints to parse JSON directly into a specified custom object, where list is fully parsed and the 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");

Register the converter with the Registrar first and 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 ();
/* The map here does not carry type hint, so by default, it is stored as Net.sf.ezmorph.bean.MorphDynaBean type object.
SYSTEM.OUT.PRINTLN (map);
/* Output:
{testone=net.sf.ezmorph.bean.morphdynabean@f73c1[
{Name=test1}
], testtwo=net.sf.ezmorph.bean.morphdynabean@186c6b2[
{Name=test2}
]}
*/
list<person> output = new ArrayList ();
for (Iterator i = map.values (). iterator (); I.hasnext ();) {
Object transformation of specified Dynabean using the Registrar
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 examples are provided below, including Jar packs and code
Jar packages and Java classes required for/files/mailingfeng/json-lib/json-lib use cases. rar

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.