티스토리 뷰

<!-- https://mvnrepository.com/artifact/org.json/json -->

<dependency>

<groupId>org.json</groupId>

<artifactId>json</artifactId>

<version>20160810</version>

</dependency>





일단 위의 코드를 pom에 추가한다. 수동으로 json을 만드는 방법도 있는데 그건 사람이 할 일이 안된다..


{    "result":200",

"foundation":"C",

item":

[

{"password":"123","id":"이인직"},

{"password":"123141","id":"허경영"},

{"password":"3124","id":"김본좌"}

]

}


예시문이 좀 이상하지만 다음의 json을 만든다고 하자.


account의 VO는 다음과 같다.


package com.testDrive.netis;


public class account {


private String id;

private String password;


public account() {

super();

// TODO Auto-generated constructor stub

}


public account(String id, String password) {

super();

this.id = id;

this.password = password;

}


public String getId() {

return id;

}


public void setId(String id) {

this.id = id;

}


public String getPassword() {

return password;

}


public void setPassword(String password) {

this.password = password;

}


@Override

public String toString() {

return "account [id=" + id + ", password=" + password + "]";

}


}




컨트롤러단의 코드는 다음과 같다.


ArrayList<account> alist = new ArrayList<account>();

alist.add(new account("이인직", "123"));

alist.add(new account("허경영", "123141"));

alist.add(new account("김본좌", "3124"));

//여기까지 arraylist 불러오는 부분

JSONObject obj = new JSONObject(); // json object 생성 

obj.put("result", 200); //넣기

obj.put("foundation", "C"); //넣기


obj.put("item", alist); // Arraylist를 그대로 넣는다. 

return obj.toString(); // String으로 반환

}


JsonArray를 사용하지 않아도 자동으로 넣어진다. 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함