首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

java中Array/List/Map/Object与Json相互转换详解

2013-02-19 
java中Array/List/Map/Object与Json互相转换详解JSON(JavaScript Object Notation): 是一种轻量级的数据交

java中Array/List/Map/Object与Json互相转换详解

JSON(JavaScript Object Notation): 是一种轻量级的数据交换格式

一、JSON建构有两种结构:对象和数组

configdata.json:

[    true,    false,    true]

Address类:

/**    * @Title: 创建Address实体类的POJO * @Description: TODO(用一句话描述该文件做什么) * @author Potter    * @date 2013-2-18 上午10:16:03 * @version V1.0    */public class Address {private String street;//街道private String city;//城市private int zip;//邮编private String tel;//第一个电话号码private String telTwo;//第二个电话号码public Address() {}public Address(String street, String city, int zip, String tel, String telTwo){this.street = street;this.city = city;this.zip = zip;this.tel = tel;this.telTwo = telTwo;}public String getStreet() {return street;}public void setStreet(String street) {this.street = street;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public int getZip() {return zip;}public void setZip(int zip) {this.zip = zip;}public String getTel() {return tel;}public void setTel(String tel) {this.tel = tel;}public String getTelTwo() {return telTwo;}public void setTelTwo(String telTwo) {this.telTwo = telTwo;}}

 

JsonTest类:

import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import net.sf.ezmorph.bean.MorphDynaBean;import net.sf.json.JSONArray;import net.sf.json.JSONFunction;import net.sf.json.JSONObject;public class JsonTest {public static void main(String args[]) {//javaArray和json互相转换javaArrayAndJsonInterChange();System.out.println("-------------------------------------");//javaList和json互相转换javaListAndJsonInterChange();System.out.println("-------------------------------------");//javaMpa和Json互转javaMapAndJsonInterChange();System.out.println("-------------------------------------");//javaObject和jsonObject互转javaObjectAndJsonInterChange();}/** * javaArray和json互相转换 */public static void javaArrayAndJsonInterChange() {// java 转数组boolean[] boolArray = new boolean[] { true, false, true };JSONArray jsonArray = JSONArray.fromObject(boolArray);String s = jsonArray.toString();System.out.println(s);// 通过json获取数组中的数据String result = readJson("configdata");JSONArray jsonR = JSONArray.fromObject(result);int size = jsonR.size();for (int i = 0; i < size; i++) {System.out.println(jsonR.get(i));}}/** * javaList和json互相转换 */public static void javaListAndJsonInterChange() {List list = new ArrayList();list.add(new Integer(1));list.add(new Boolean(true));list.add(new Character('j'));list.add(new char[] { 'j', 's', 'o', 'n' });list.add(null);list.add("json");list.add(new String[] { "json", "-", "lib" });// list转JSONArrayJSONArray jsArr = JSONArray.fromObject(list);System.out.println(jsArr.toString(4));// 从JSON串到JSONArrayjsArr = JSONArray.fromObject(jsArr.toString());// --从JSONArray里读取// print: jsonSystem.out.println(((JSONArray) jsArr.get(6)).get(0));}/** * javaMpa和Json互转 */public static void javaMapAndJsonInterChange() {Map map = new LinkedHashMap();map.put("integer", new Integer(1));map.put("boolean", new Boolean(true));map.put("char", new Character('j'));map.put("charArr", new char[] { 'j', 's', 'o', 'n' });// 注:不能以null为键名,否则运行报net.sf.json.JSONException:// java.lang.NullPointerException:// JSON keys must not be null nor the 'null' string.map.put("nullAttr", null);map.put("str", "json");map.put("strArr", new String[] { "json", "-", "lib" });map.put("jsonFunction", new JSONFunction(new String[] { "i" },"alert(i)"));map.put("address", new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098"));// map转JSONArrayJSONObject jsObj = JSONObject.fromObject(map);System.out.println(jsObj.toString(4));// 从JSON串到JSONObjectjsObj = JSONObject.fromObject(jsObj.toString());//第一种方式:从JSONObject里读取// print: jsonSystem.out.println(jsObj.get("str"));// print: address.city = Seattle, WA  System.out.println("address.city = " + ((JSONObject) jsObj.get("address")).get("city"));  //第二种方式:从动态Bean里读取数据,由于不能转换成具体的Bean,感觉没有多大用处MorphDynaBean mdBean = (MorphDynaBean) JSONObject.toBean(jsObj);// print: jsonSystem.out.println(mdBean.get("str"));//print: address.city = Seattle, WA  System.out.println("address.city = " + ((MorphDynaBean) mdBean.get("address")).get("city"));  }/** * javaObject和jsonObject互转 */public static void  javaObjectAndJsonInterChange(){Address address=new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098");//object转JSONObjectJSONObject jsObj = JSONObject.fromObject(address);System.out.println(jsObj.toString(4));//JsonObject转java ObjectAddress addressResult=(Address) JSONObject.toBean(jsObj, Address.class);System.out.println("address.city = "+ addressResult.getCity());System.out.println("address.street="+addressResult.getStreet());System.out.println("address.tel = "+ addressResult.getTel());System.out.println("address.telTwo="+addressResult.getTelTwo());System.out.println("address.zip="+addressResult.getZip());}/** * 读取json文件 * @param fileName 文件名,不需要后缀 * @return */public static String readJson(String fileName) {String result = null;try {File myFile = new File("./config/" + fileName + ".json");FileReader fr = new FileReader(myFile);char[] contents = new char[(int) myFile.length()];fr.read(contents, 0, (int) myFile.length());result = new String(contents);fr.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return result;}}


哈哈~  没想到其实挺简单的!!!

 

参看文章:

http://jiangzhengjun.iteye.com/blog/463769

http://blog.csdn.net/chenzhehui/article/details/4067482

http://baike.baidu.com/view/136475.htm

热点排行