Java 與 Json的互相轉換

FROM:http://blog.sina.com.cn/s/blog_663bfedc0100tap3.html 

這幾天一直在做Java解析Json數據的一個項目,因爲初識json,所以很多東西都是有着懵懂的認識。這裏寫下我解析時遇到的問題和收穫。

   我解析json時用到的是json-lib包。下載地址:http://json-lib.sourceforge.net。用這個包時,還要用到其他幾個支持包:commons-lang.jarcommons-logging.jarcommons-beanutils.jarxom-1.0-2005-01-05.jarezmorph-1.0.1.jar,以上包都可在http://json-lib.sourceforge.net下載。

 

  先給出2個簡單的例子。

1.java2json

樣例:

public class testJson{
 public static void main(String[] args) {
    String json = "{\"name\":\"reiz\"}";
    JSONObject jsonObj = JSONObject.fromObject(json);
    String name = jsonObj.getString("name");
     
    jsonObj.put("initial", name.substring(0, 1).toUpperCase());

    String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" };
    jsonObj.put("likes", likes);

    Map<String, String> ingredients = new HashMap<String, String>();
    ingredients.put("apples", "3kg");
    ingredients.put("sugar", "1kg");
    ingredients.put("pastry", "2.4kg");
    ingredients.put("bestEaten", "outdoors");
    jsonObj.put("ingredients",ingredients);
     
    System.out.println(jsonObj);
     }

輸出結果:

{"name":"reiz","initial":"R","likes":["JavaScript","Skiing","Apple Pie"],"ingredients":{"apples":"3kg","pastry":"2.4kg","bestEaten":"outdoors","sugar":"1kg"}}

java2json的資料網上很多,此不具體研究。

 

2.javafromjson

例子:

public class testJson{
 public static void main(String[] args) {
  String json = "{x:'1',y:'2',userId:'112',element:[{id:'123',name:'haha'},{id:'456',name:'hehe'}]}";
  
   JSONObject obj = JSONObject.fromObject(json);
   String x = obj.getString("x");
   String userid = obj.getString("userId");
   System.out.println("x is:" + x);
   System.out.println("userId is:" + userid);
  
   // 數組array結果:[{"id":"123","name":"haha"},{"id":"456","name":"hehe"}]
   JSONArray jsonArray = obj.getJSONArray("element");
   for (int i = 0; i < jsonArray.size(); i++) {
    System.out.println("element " + i + " :" + jsonArray.get(i));
   }
 }
}    

輸出:

x is:1
userId is:112
element 0 :{"id":"123","name":"haha"}
element 1 :{"id":"456","name":"hehe"}

從上例可以看出,若取某一數組,可用json.get(i)取出。若想繼續取出數組中第i個元素內的某一個值,如取出數組第一個元素中id的值,可用(JSONObject)json.get(0).getInt("id")取出,爲了看出細節,我們設取第二個元素中name的值,代碼如下:

     JSONObject obj2 = JSONObject.fromObject(array.get(1));
     System.out.println(obj2.getString("name"));

   輸出結果爲 hehe

   可以看出一般步驟爲:將要目標字符串轉爲JSON對象(JSONObject.fromObject()方法),再根據相應方法取出該對象中需要的值。

    如果我們要將json反序列化爲javabean呢?

    String jsonStr = "{x:1,\"userId\":\"112\",element:[{id:'123',name:'haha'},{id:'456',name:'hehe'}]}";
   Map<String,Class<?>> m  = new HashMap<String,Class<?>>();
   m.put("x", Integer.class);
   m.put("userId", String.class);
   m.put("element",Element.class);
 
   Jsontobean myBean  = (Jsontobean)JSONObject.toBean( JSONObject.fromObject(jsonStr), Jsontobean.class, m );
   System.out.println("x: " + myBean.getX());
   System.out.println("userId: " + myBean.getUserId());
 
   for(Element e : myBean.getElement()){
     System.out.println(e.getId() +"," + e.getName());
   }

 

public class Jsontobean {
    private int x = 1;
    private String userId = "112";
    private List<Element> element;
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public List<Element> getElement() {
        return element;
    }
    public void setElement(List<Element> element) {
        this.element = element;
    }  
}

 

public class Element {
    private int id;
    private String name;
    private Element source;
    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 void setSource(Element source) {
  this.source = source;
 }
 public Element getSource() {
  return source;
 }
    public String toString(){
         return "" + id + "," + name;
    }
}

輸出:

x: 1
userId: 112
123,haha
456,hehe

-------

附:jsontojava對象

1)JSONObject to DynaBean

所謂動態bean即是java運行的時候根據情況創建的,而不是程序員已經寫好了的Bean。JsonLib會自動根據Json格式數據創建字段,然後創建一個包含這些字段的Object。代碼片段:

  1. String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}";   
  2. JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );   
  3. DynaBean bean = (DynaBean) JSONSerializer.toJava( jsonObject );   
  4. assertEquals( "JSON", bean.get("string") );         
  5. assertEquals( new Integer(1), bean.get("integer") );         
  6. assertEquals( new Double(2.0), bean.get("double") );         
  7. assertEquals( Boolean.TRUE, bean.get("boolean") );      


2)JSONObject to JavaBean

JSONLIB在轉換的時候會自動查找關係,比如子類和父類
例如JSON數據源
    String s = "{'shopList':[{name:'重量',property:'p1'},{name:'尺寸',property:'p2'}, {name:'顯卡 類型',property:'p3'},{name:'硬盤容量',property:'p4'},{name:'處理器 ',property:'p5'},{name:'內存',property:'p6'},{name:'型號',property:'p7'}, {name:'貨號',property:'p8'},{name:'品牌',property:'p9'}]}";
   存入Map
   map.put("shopList", Shop.class);
   ShopList shopList = (ShopList) JSONObject.toBean(JSONObject.fromObject(s), ShopList.class, map);
JSONObject.toBean()方法的三個參數分別表示數據源對應的JSON對象,轉化後的對象ShopList和數據源map。
這種方法和動態轉換的區別在於,動態轉換僅僅只是轉爲Object,而靜態轉換是轉換爲已經定義過的實體類,會自動映射。JSONObject.toBean()的參數介紹。

 

  這裏,衷心謝謝各位給予我的幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章