JSON與JAVA資料的相互轉換

來源:互聯網
上載者:User

標籤:

 

http://www.cnblogs.com/linjiqin/archive/2011/09/19/2181408.html

 

import net.sf.json.JSONArray;import net.sf.json.JSONException;import net.sf.json.JSONObject;import net.sf.json.JSONSerializer;            /**     * json對象轉換為java對象     *      * @throws JSONException     */    @Test    public void jsonToJava(){        String json="[{\"addTime\":\"2011-09-19 14:23:02\",\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]";        //接收{}對象,此處接收數組對象會有異常        if(json.indexOf("[")!=-1){            json=json.replace("[", "");        }        if(json.indexOf("]")!=-1){            json=json.replace("]", "");        }        JSONObject obj=new JSONObject().fromObject(json);        SimInfo simInfo=(SimInfo)JSONObject.toBean(obj, SimInfo.class);        System.out.println("obj: "+simInfo);        System.out.println(simInfo.getAddTime());        System.out.println(simInfo.getIccid());        System.out.println(simInfo.getImei());        System.out.println(simInfo.getImsi());        System.out.println(simInfo.getPhoneType());        System.out.println(simInfo.getRemark());        System.out.println(simInfo.getTel());        System.out.println(simInfo.getId());                DaoFactory.getSimInfoDao().add(simInfo);    }    /**     * 將json轉換為java集合對象     */    @Test    public void jsonToJavas(){        String jsons="[{\"addTime\":\"2011-09-19 14:23:02\",\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}," +                     "{\"addTime\":\"2011-11-11 14:23:02\",\"iccid\":\"2222\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]";        List<SimInfo> simInfos = getJavaCollection(new SimInfo(),jsons);        System.out.println(simInfos.size());        for(SimInfo simInfo:simInfos){            System.out.println("addTime: "+simInfo.getAddTime());            System.out.println("=========");        }            }    /**     * 封裝將json對象轉換為java集合對象     *      * @param <T>     * @param clazz     * @param jsons      * @return     */    private <T> List<T> getJavaCollection(T clazz, String jsons) {        List<T> objs=null;        JSONArray jsonArray=(JSONArray)JSONSerializer.toJSON(jsons);        if(jsonArray!=null){            objs=new ArrayList<T>();            List list=(List)JSONSerializer.toJava(jsonArray);            for(Object o:list){                JSONObject jsonObject=JSONObject.fromObject(o);                T obj=(T)JSONObject.toBean(jsonObject, clazz.getClass());                objs.add(obj);            }        }        return objs;    }        /**     * java對象轉換為json對象     *      * @throws JSONException     */    @Test    public void javaToJson(){        SimInfo simInfo=new SimInfo();        simInfo.setAddTime(UtilTool.dateToStr(new Date(), null));        simInfo.setIccid("1111");        simInfo.setImei("2222");        simInfo.setImsi("3333");        simInfo.setPhoneType(4);        simInfo.setRemark("aaaa");        simInfo.setTel("5555");        //java對象轉換為json對象        String json=new JSONArray().fromObject(simInfo).toString();        //json: [{"addTime":"2011-09-19 14:23:02","iccid":"1111","id":0,"imei":"2222","imsi":"3333","phoneType":"4444","remark":"aaaa","tel":"5555"}]        System.out.println("json: "+json);    }

 

jackson-core-asl-1.7.2.jar   

jackson-mapper-asl-1.7.2.jar

 //將一個Java對象轉換成JSON            StringWriter writer = new StringWriter();            ObjectMapper mapper = new ObjectMapper();            mapper.writeValue(writer, simInfo);            String json=writer.toString();

 

基於json-lib.jar包Json執行個體程式1.JSONObject to DynaBeanString json = "{name=\"json\",bool:true,int:1,double:2.2}";JSONObject jsonObject = JSONObject.fromObject(json);//抽象的寫法:DynaBean bean = (DynaBean) JSONSerializer.toJava( jsonObject );   Object bean = JSONObject.toBean(jsonObject);//Object bean1 = JSONSerializer.toJava(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"));             2.JSONObject to JavaBeanString json = "{name:\"zhangsan\",age:25,hight:1.72,sex:true}";JSONObject jsonObject = JSONObject.fromObject(json);UserBean bean = (UserBean) JSONObject.toBean(jsonObject, UserBean.class);System.out.println(jsonObject);理論上,這樣就可以了,但時,有異常Caused by: java.lang.NoSuchMethodException: com.json.Json$UserBean.<init>()             3.JSONArray to ListString json = "[\"first\",\"second\"]";JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(json);List output = (List) JSONSerializer.toJava(jsonArray);     4.JSONArray to arrayString json = "[\"first\",\"second\"]";JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(json);JsonConfig jsonConfig = new JsonConfig();jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);Object[] output = (Object[]) JSONSerializer.toJava(jsonArray, jsonConfig);Object[] expected = new Object[] { "first", "second" };ArrayAssertions.assertEquals(expected, output);                   5.JSON 字串 專為 JavaBean(劉慧斌demo 示範需要的jar包在附件裡)String str="[{\"id\":\"328\",\"mestype\":\"inbox\"},{\"id\":\"327\",\"mestype\":\"inbox\"},{\"id\":\"279\",\"mestype\":\"already\"},{\"id\":\"278\",\"mestype\":\"already\"},{\"id\":\"277\",\"mestype\":\"already\"},{\"id\":\"310\",\"mestype\":\"inbox\"},{\"id\":\"308\",\"mestype\":\"inbox\"},{\"id\":\"305\",\"mestype\":\"inbox\"},{\"id\":\"304\",\"mestype\":\"inbox\"},{\"id\":\"303\",\"mestype\":\"inbox\"}]";  JSONArray  jsonArray=(JSONArray) JSONSerializer.toJSON(str);  List list=(List)JSONSerializer.toJava(jsonArray);        for (Object  obj: list) {         JSONObject jsonObject = JSONObject.fromObject(obj);      MessageBean bean = (MessageBean) JSONObject.toBean(jsonObject, MessageBean.class);   String id=bean.getId()+"";   String type=bean.getMestype();   System.out.println(id+" "+type);  }  System.out.println(list.size());

 

JSON與JAVA資料的相互轉換

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.