BACK END/jsp

jsp에서 json encode

자코린이 2022. 7. 1. 20:27

json 라이브러리를 다운 받습니다.

https://mvnrepository.com/artifact/org.json/json/20220320

 

Maven Repository: org.json » json » 20220320

JSON is a light-weight, language independent, data interchange format. See http://www.JSON.org/ The files in this package implement JSON encoders/decoders in Java. It also includes the capability to convert between JSON and XML, HTTP headers, Cookies, and

mvnrepository.com

 

저번에 만든 db.jsp와 dao.jsp를 사용하겠습니다.

2022.07.01 - [BACK END/jsp] - JSP와 DB 연결

 

JSP와 DB 연결

스프링을 사용하다보면 JSP만으로 코딩을 할 일이 많이 없습니다. 하지만 적은 인원으로 빠른 개발이 필요한 경우 JSP를 사용할 수 있습니다. (여러분 그냥 PHP, node, Django 쓰세요...) 일단 jsp 만들

jacorinne.tistory.com

제가 원하는 json 형식은 아래처럼 나와야 합니다.

json객체안에 json배열이 있고, 그 안에 json객체가 와야 합니다.

{ "name" : [{"name" : "nameVal", "count" : "countVal"}]}
<%@  include file = "dao.jsp" %>

<%
    ArrayList<HashMap<String,String>> list = getData();
    JSONObject obj=new JSONObject(); 
    HashMap<String,String> hashMap = new HashMap();
    JSONArray jsonArr = new JSONArray();
    JSONObject obj1=new JSONObject();

    for( int i = 0; i < list.size(); i++ ){
        hashMap = list.get(i);

        obj.put("name", hashMap.get("nameVal"));
        obj.put("count", hashMap.get("countVal"));

        jsonArr.put(obj);        
    }
    
    obj1.put("name", jsonArr);
 
%>
<%=obj1%>

 

이처럼 만들면 json encode하는 것을 확인 할 수 있습니다.

(PHP는 하나의 함수만 필요하다는 것을 명심하세요... 모두 도망쳐)

'BACK END > jsp' 카테고리의 다른 글

JSP와 DB 연결  (0) 2022.07.01