先給出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
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
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
return element;
}
public void setElement(List
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。代碼片段:
String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}";
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );
DynaBean bean = (DynaBean) JSONSerializer.toJava( jsonObject );
assertEquals( "JSON", bean.get("string") );
assertEquals( new Integer(1), bean.get("integer") );
assertEquals( new Double(2.0), bean.get("double") );
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()的參數介紹。