Use json-lib for conversion between Java and JSON

Source: Internet
Author: User

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 conversion.

2. json-lib home page: http://json-lib.sourceforge.net/

3. Execution Environment

The following class libraries are 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. Function example

    Here we use the JUnit-Case example to show the sample code.

    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 all parsed using JSONArray ** Map, custom type is parsed using JSONObject * Map can be understood as an object, the key/value pair can be understood as the property/attribute value * of the object, that is, {key1: value1, key2, value2 ......} ** 1. JSONObject is a name: values set. The get (key) method obtains the value part (string) corresponding to the key * through its getJSONObject (key) you can get a JSONObject, --> to map, * through its getJSONArray (key), you can get a JSONArray, * ** // convert a general array 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]} // convert the Collection object to 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"]} // converts the string json to json. Use JSONArray or JSONObject @ Test public void testJsonStrToJSON () based on the situation () {JSONArray jsonArray = JSONArray. fromObject ("['json', 'is ', 'easy']"); System. out. println (jsonArray); // prints ["json", "is", "easy"]} // Map is converted to json, which uses 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);} // convert the composite bean to 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 (""); cardNum. add (new Person ("test"); bean. setCardNum (cardNum); JSONObject jsonObject = JSONObject. fromObject (bean); System. out. println (jsonObject);} // convert a common json type 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: []} "; 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 object, including 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 () ;}}// parse json into a composite object, including Map @ Test public void testJSONToBeanHavaMap () {// regard Map as a 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); // usage suggestion: json is directly parsed as a specified custom object, in which List is completely parsed, and Map is not completely parsed as MyBeanWithPerson diyBean = (MyBeanWithPerson) JSONObject. toBean (JSONObject. fromObject (json), MyBeanWithPerson. class, classMap); System. out. println (diyBean); System. out. println ("do the list release"); List
       
        
    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 in the register first, and use the class MorpherRegistry morpherRegistry = JSONUtils IN the ezmorph package. getMorpherRegistry (); Morpher dynaMorpher = new BeanMorpher (Person. class, morpherRegistry); morpherRegistry. registerMorpher (dynaMorpher); Map map = diyBean. getMap ();/* the map here does not imply the type, so it is saved as net by default. sf. ezmorph. bean. morphDynaBean 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
        
         
    Output = new ArrayList (); for (Iterator I = map. values (). iterator (); I. hasNext ();) {// use the Register to perform object conversion for the specified DynaBean. output. add (Person) morpherRegistry. morph (Person. class, I. next ();} for (Person p: output) {System. out. println (p. getName ();/* output: test1 test2 */}}}
        
       

    5. The following provides the resources required for the preceding example, including the jar package and code.
    /Files/mailingfeng/json-lib/json-libuse case jarpack and Java class .rar


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.