java对象和json对象之间互相转换

json和java对象转换,有好几种常用的第三方jar包,比如:谷歌的gson,aliababa的fastjson,JSON-lib和Jackson

自己在调试接口时,发现如果从 json串转为java对象,最好是用gson,因为即使对象中有json中不存在的字段,可以成功转换,不会报错

 

这里使用JSON-lib写个例子

需要jar包:

commons-beanutils-1.7.0.jar
commons-lang-2.1.jar
ezmorph-1.0.2.jar
json-lib-1.1-jdk15.jar

  1 package com.kenneth.test;
  2 
  3 import java.util.ArrayList;
  4 import java.util.Collection;
  5 import java.util.Iterator;
  6 import java.util.List;
  7 
  8 import net.sf.json.JSONArray;
  9 import net.sf.json.JSONObject;
 10 
 11 /**
 12  * Created by Administrator on 2016/2/1 0001.
 13  */
 14 public class JsonAndJava {
 15 
 16     public static void main(String[] args) {
 17         TestJsonBean();
 18         TestJsonAttribute();
 19         TestJsonArray();
 20     }
 21 
 22     @SuppressWarnings("rawtypes")
 23     private static void TestJsonArray() {
 24         Student student1 = new Student();
 25         student1.setId(1);
 26         student1.setName("jag");
 27         student1.setSex("man");
 28         student1.setAge(25);
 29         student1.setHobby(new String[]{"篮球","游戏"});
 30 
 31         Student student2 = new Student();
 32         student2.setId(2);
 33         student2.setName("tom");
 34         student2.setSex("woman");
 35         student2.setAge(23);
 36         student2.setHobby(new String[]{"上网","跑步"});
 37 
 38         List<Student> list = new ArrayList<Student>();
 39         list.add(student1);
 40         list.add(student2);
 41 
 42         JSONArray jsonArray = JSONArray.fromObject(list);
 43         System.out.println(jsonArray.toString());
 44 
 45         JSONArray new_jsonArray=JSONArray.fromObject(jsonArray.toArray());
 46 //        Collection java_collection=JSONArray.toCollection(new_jsonArray);
 47 //        if(java_collection!=null && !java_collection.isEmpty())
 48 //        {
 49 //            Iterator it=java_collection.iterator();
 50 //            while(it.hasNext())
 51 //            {
 52 //                JSONObject jsonObj=JSONObject.fromObject(it.next());
 53 //                Student stu=(Student) JSONObject.toBean(jsonObj,Student.class);
 54 //                System.out.println(stu.getName());
 55 //            }
 56 //        }
 57     }
 58 
 59     private static void TestJsonAttribute() {
 60         /**
 61          * 创建json对象并为该对象设置属性
 62          */
 63         JSONObject jsonObj = new JSONObject();
 64         jsonObj.put("Int_att",25);//添加int型属性
 65         jsonObj.put("String_att","str");//添加string型属性
 66         jsonObj.put("Double_att",12.25);//添加double型属性
 67         jsonObj.put("Boolean_att",true);//添加boolean型属性
 68         //添加JSONObject型属性
 69         JSONObject jsonObjSon = new JSONObject();
 70         jsonObjSon.put("id", 1);
 71         jsonObjSon.put("name", "tom");
 72         jsonObj.put("JSONObject_att",jsonObjSon);
 73         //添加JSONArray型属性
 74         JSONArray jsonArray = new JSONArray();
 75         jsonArray.add("array0");
 76         jsonArray.add("array1");
 77         jsonArray.add("array2");
 78         jsonArray.add("array3");
 79         jsonObj.put("JSONArray_att", jsonArray);
 80         System.out.println(jsonObj.toString());
 81         System.out.println("Int_att:"+jsonObj.getInt("Int_att"));
 82         System.out.println("String_att:"+jsonObj.getString("String_att"));
 83         System.out.println("Double_att:"+jsonObj.getDouble("Double_att"));
 84         System.out.println("Boolean_att:"+jsonObj.getBoolean("Boolean_att"));
 85         System.out.println("JSONObject_att:"+jsonObj.getJSONObject("JSONObject_att"));
 86         System.out.println("JSONArray_att:"+jsonObj.getJSONArray("JSONArray_att"));
 87     }
 88 
 89     /**
 90      * java对象与json对象互相转换
 91      */
 92     private static void TestJsonBean() {
 93         /**
 94          * 创建java对象
 95          */
 96         Student student = new Student();
 97         student.setId(1);
 98         student.setName("jag");
 99         student.setSex("man");
100         student.setAge(25);
101         student.setHobby(new String[]{"篮球","上网","跑步","游戏"});
102         /**
103          * java对象转换成json对象,并获取json对象属性
104          */
105         JSONObject jsonStu = JSONObject.fromObject(student);
106         System.out.println("bean-106:"+jsonStu.toString());
107         System.out.println("bean-107:"+jsonStu.getJSONArray("hobby"));
108         /**
109          * json对象转换成java对象,并获取java对象属性
110          */
111         Student stu = (Student) JSONObject.toBean(jsonStu, Student.class);
112         System.out.println(stu.getName());
113         /**
114          * 创建json对象
115          */
116         JSONObject jsonObj = new JSONObject();
117         jsonObj.put("id",1);
118         jsonObj.put("name","张勇");
119         jsonObj.put("sex","男");
120         jsonObj.put("age",24);
121         //jsonObj.put("hobby",new String[]{"上网","游戏","跑步","音乐"});
122         //System.out.println(jsonObj.toString());
123         /**
124          * json对象转换成java对象
125          */
126         Student stud = (Student) JSONObject.toBean(jsonObj,Student.class);
127         System.out.println(stud.getName());
128     }
129 }

 

二. json串转为 泛型对象

1. 使用fastjson

       BasEntity<User> obj = JSON.parseObject( jsonStr, new TypeReference<BasEntity<User>>(){});

2. 使用gson

Type  jsonType = new TypeToken<JsonRootBean<TripResultData>>() {}.getType();

JsonRootBean<List<TripResultData>>   rootBean =  new Gson().fromJson(jsonStr, jsonType);

 

posted @ 2016-02-01 16:02  NewLife365  阅读(759)  评论(0编辑  收藏  举报