제이슨(json)
제이손 라이브러리
1. json-lib-2.4-jdk15.jar1
2. EZmorph 1.0.6
<dependency>
<groupId>net.sf.ezmorph</groupId>
<artifactId>ezmorph</artifactId>
<version>1.0.6</version>
</dependency>
제이슨 입력
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
//{변수:값, 변수:값…} JSONObject
// [{},{},{},{}] JSONArray
JSONObject obj=new JSONObject();
obj.put(“name”, “박문수”);
obj.put(“sex”, “남자”);
obj.put(“age”, 30);
FileOutputStream fos=new FileOutputStream(“./info.json”);
fos.write(obj.toJSONString().getBytes(“UTF-8”));//바이트로 변환. 이때 UTF-8을 줘야 한글이 깨지지 않는다
fos.close();
System.out.println(“데이터 저장 완료”);
}catch(Exception ex){System.out.println(ex.getMessage());}
}
제이슨 출력
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
//제이슨 파서가 제이슨 번역기다.
JSONParser parser=new JSONParser();
Object obj2=parser.parse(new InputStreamReader(new FileInputStream(“./info.json”),”UTF-8″));
JSONObject jsonObj=(JSONObject)obj;
String name=(String)jsonObj.get(“name”);
String sex=(String)jsonObj.get(“sex”);
Long age=Long.valueOf(jsonObj.get(“age”).toString());
System.out.println(“Name”+name);
System.out.println(“Sex”+sex);
System.out.println(“Age”+age);
}catch(Exception ex){System.out.println(ex.getMessage());}
}
제이슨 입력 2
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
AddressBook ad=createAddressBook();
JSONObject obj=JSONObject.fromObject(JSONSerializer.toJSON(ad));
System.out.println(obj.toString());
FileOutputStream fos=new FileOutputStream(“./address.json”);
fos.write(obj.toString().getBytes(“UTF-8”));
fos.close();
}catch(Exception ex){System.out.println(ex.getMessage());}
}
제이슨 출력 2
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
AddressBook ad=createAddressBook();
JSONObject obj=JSONObject.fromObject(JSONSerializer.toJSON(ad));
JSONArray users=(JSONArray)obj.get(“user”);
JSONObject user=(JSONObject)users.get(0);
System.out.println(“Name:”+user.get(“name”));
System.out.println(“Phone:”+user.get(“phone”));
System.out.println(“Address:”+user.get(“Address”));
JSONObject emails=(JSONObject)user.get(“emails”);
JSONArray email=(JSONArray)emails.get(“email”);
for(int i=0;i<email.size();i++){
JSONObject temp=(JSONObject)email.get(i);
System.out.println(temp.get(“id”)+” “+temp.get(“emailAddr”));
}
}catch(Exception ex){System.out.println(ex.getMessage());}
}
구글에서 도서 제이슨 얻어오기