Conversion between JSON strings and Java objects

Source: Internet
Author: User

Recently, my younger brother used JSON. After learning about it, it's quite simple. He just needs to make some preparations before getting started.

Download the jarpackage at http://json-lib.sourceforge.net/on the JSON official website. You can also see on the official website that other jar packages are required to use JSON, which is listed on the official website as follows:

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

Of course, we can also use a relatively new version of the jar package, but it should be noted that the commons-lang jar needs to select a version earlier than 2.6 (including 2.6 of course ), because the package name in the jar package has changed since version 3.3.0.1 and is used again, an error is reported, of course, I did not go into which jar package caused it. (If you have any idea, please leave a message to me. Thank you ).

JSON-to-Java objects often use two classes of net. SF. JSON. jsonobject and net. SF. JSON. jsonarray can be seen through the class name. The former is for unordered sets, and the latter is for ordered sets such as list.

A Brief Introduction to the following methods: The jsonobject. fromobject (Object object) method uses a Java object as a parameter and returns a jsonobject object, which is a string in JSON format;

Jsonarray. fromobject (Object object) receives a collection.

First define an object class:

package com.bao.json.demo;import java.util.ArrayList;package com.bao.json.domain;public class User {private int id;private String name;private boolean gender;private float price;public User() {super();}public User(int id, String name) {super();this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public boolean isGender() {return gender;}public void setGender(boolean gender) {this.gender = gender;}public float getPrice() {return price;}public void setPrice(float price) {this.price = price;}}

The following are tool classes:

Package COM. bao. common. util; import Java. util. arraylist; import Java. util. hashmap; import Java. util. iterator; import Java. util. list; import Java. util. map; import net. SF. JSON. jsonarray; import net. SF. JSON. jsonobject;/*** @ Description: JSON tool class * The ordered set starts with '[' and ends with ']'. The other sets start with '{' and end. * You can use jsonarray or jsonobject to convert a Java object to a string. * @ Author: BAO * @ Date: Dec 24,201 1 * @ see jsonarray */public class jsonutil {/*** @ descrip Tion: Convert pojo to a JSON string * @ Param OBJ * @ return string */public static string bean2jsonstr (Object OBJ) {jsonobject jsonobj = jsonobject. fromobject (OBJ); Return jsonutil. tostring (jsonobj);}/*** @ Description: Convert the JSON string to a pojo object * @ Param jsonstr * @ Param pojo * @ return object */public static object jsonstr2bean (string jsonstr, class <?> Clazz) {object OBJ; jsonobject = jsonobject. fromobject (jsonstr); OBJ = jsonobject. tobean (jsonobject, clazz); Return OBJ;}/*** @ Description: Convert the JSON string to map <string, Object> * @ Param jsonstr * @ return Map <string, object> */public static Map <string, Object> jsonstr2map (string jsonstr) {Map <string, Object> result = new hashmap <string, Object> (); jsonobject jsonobj = jsonobject. fromobject (jsonstr); it Erator <?> Keys = jsonobj. keys (); string key; object val; while (keys. hasnext () {key = (string) keys. next (); val = jsonobj. get (key); result. put (Key, Val);} return result;}/*** @ Description: Convert the JSON string to list. The internal object is an object, manually convert to the specified object type * @ Param jsonstr * @ Param pojo * @ return list */public static list jsonstr2list (string jsonstr, class clazz) {list result = new arraylist (); jsonarray = jsonarray. fromobject (JSO NSTR); jsonobject jsonobj; object pojoval; For (INT I = 0; I <jsonarray. size (); I ++) {jsonobj = jsonarray. getjsonobject (I); pojoval = jsonobject. tobean (jsonobj, clazz); result. add (pojoval);} return result;} public static object [] jsonstr2objectarray (string jsonstr) {jsonarray = jsonarray. fromobject (jsonstr); object [] result = new object [jsonarray. size ()]; for (INT I = 0; I <jsonarray. size (); I + +) {Result [I] = jsonarray. get (I);} return result;}/*** @ Description: converts an object to a string * @ Param OBJ specified object, the default value is "" * @ return string */public static string tostring (Object OBJ) {return tostring (OBJ, "") ;}/ *** @ description: convert an object to a string * @ Param OBJ specified object * @ Param ultultstr is a null default string * @ return string */public static string tostring (Object OBJ, string defaultstr) {string result = defaultstr; If (OBJ! = NULL) {result = obj. tostring ();} return result ;}}

Which of the following has been tested by junit4.7:

package com.bao.common.util;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import org.junit.Test;import com.bao.json.domain.User;public class JsonUtilTest {@Testpublic void testBeanO2JsonStr() {String result = JsonUtil.bean2JsonStr(getUser());System.out.println(result);}@Testpublic void testJsonStr2Bean() {Object obj = JsonUtil.jsonStr2Bean(JsonUtil.bean2JsonStr(getUser()),User.class);System.out.println(obj);}@Testpublic void testJsonStr2List(){List list = JsonUtil.jsonStr2List(getFromList().toString(), User.class);System.out.println(list);}@Testpublic void testJsonStr2Map(){Map<?, ?> map = JsonUtil.jsonStr2Map(getFromMap().toString());System.out.println(map);}@Testpublic void testJsonStr2ObjectArray(){Integer[] result = {1,2,3};Object[] objs  = JsonUtil.jsonStr2ObjectArray(JSONArray.fromObject(result).toString());for(int i=0;i<objs.length;i++){System.out.println(objs[i]);}}private static User getUser() {User user = new User();user.setId(11);user.setName("test");user.setGender(true);user.setPrice(2.7f);return user;}private static List<User> getList() {User user = getUser();List<User> users = new ArrayList<User>();for (int i = 0; i < 10; i++) {users.add(user);}return users;}private static JSONArray getFromList() {List<User> users = getList();return JSONArray.fromObject(users);}public static JSONObject getFromMap() {Map<String, Object> map = new HashMap<String, Object>();map.put("ua", getUser());map.put("list", getList());return JSONObject.fromObject(map);}}

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.