2011年4月20日 星期三

Example:Java讀JSON

Requirement
JSON的官網中,找出相對應的程式語言的套件(我是用這套org.json)

Implementation
import org.json.*;

public class Main {

public static void main(String[] args) {
// TODO Auto-generated method stub
GenerateJSON myJsonString = new GenerateJSON();
JSONObject tempObj = null;

try {
JSONObject jsonObj = new JSONObject(myJsonString.generateJSON());
tempObj = new JSONObject(jsonObj.get("UserProfile").toString());
System.out.println("/*------------UserProfile---------------*/");
System.out.print(tempObj.get("userName") + " ");
System.out.print(tempObj.get("password") + " ");
System.out.print(tempObj.get("sex"));
System.out.println();

System.out.println("/*------------MoneyPlan---------------*/");
JSONObject moneyPlan = new JSONObject(jsonObj.get("MoneyPlan")
.toString());
tempObj = new JSONObject(moneyPlan.get("Monday").toString());
System.out.print("[Monday]");
System.out.print(tempObj.get("dinner") + "\t");
System.out.print(tempObj.get("breakfast") + "\t");
System.out.print(tempObj.get("lunch") + "\n");

tempObj = new JSONObject(moneyPlan.get("Tuesday").toString());
System.out.print("[Tuesday]");
System.out.print(tempObj.get("dinner") + "\t");
System.out.print(tempObj.get("breakfast") + "\t");
System.out.print(tempObj.get("lunch") + "\n");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}


import org.json.*;
//{
// "MoneyPlan":{
// "Monday":{
// "dinner":"100",
// "breakfast":"50",
// "lunch":"100"
// },
// "Tuesday":{
// "dinner":"200",
// "breakfast":"55",
// "lunch":"150"
// }
// },
// "UserProfile":{
// "userName":"aaa",
// "password":"bbb",
// "Sex":"Boy"
// }
//}

public class GenerateJSON {

public String generateJSON() {
JSONObject jsonObj = new JSONObject();
JSONObject detailObj = new JSONObject();
JSONObject detailObj2 = new JSONObject();

try {
detailObj.put("userName", "9836002");
detailObj.put("password", "9836002");
detailObj.put("sex", "Boy");
jsonObj.put("UserProfile", detailObj);

detailObj2.put("breakfast", "50");
detailObj2.put("lunch", "100");
detailObj2.put("dinner", "100");

detailObj = new JSONObject();
detailObj.put("Monday", detailObj2);

detailObj2 = new JSONObject();
detailObj2.put("breakfast", "55");
detailObj2.put("lunch", "150");
detailObj2.put("dinner", "200");

detailObj.put("Tuesday", detailObj2);
jsonObj.put("MoneyPlan", detailObj);

} catch (JSONException ex) {
System.out.println(ex.toString());
}

return jsonObj.toString();
}
}


Reference:
JSON
JSON in JAVA 的簡單程式範例

沒有留言: