Simple Json Parser 를 이용한 JAVA에서 Json 사용하기

Java 2017. 3. 14. 12:00
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Simple Json Parser 를 이용한 JAVA에서 Json 사용하기



해당 포스팅은 json-simple 라이브러리를 사용하기에


Maven 을 이용하여 json-simple 라이브러리를 다운로드 하도록


pom.xml 파일에 dependency를 추가해주도록 하자



<!-- JSON Simple Parser -->

      <dependency>

        <groupId>com.googlecode.json-simple</groupId>

        <artifactId>json-simple</artifactId>

        <version>1.1</version>

      </dependency>




본 포스팅에 나올 코딩은 

이렇게 아래↓ 첨부 해 놓았으니  참고!


jsontest.json

Test.java






첨부 파일중 jsontest.json 이라는 파일에

들어있는 내용은 이렇다.



jsontest.json


{

   "pageInfo": {

         "pageName": "abc",

         "pagePicpoc": "http://abc.com/cont.jpg"

    },

    "posts": [

         {

              "post_id": "123456789012_123456789012",              

              "picpoc": "http://example.com/photo.jpg",

              "nameOfPersonWhoPosted": "Jane Doe",

              "message": "Sounds cool. Can't wait to see it!",              

         }

    ]

}


이 json 형태의 내용을 JAVA에서 불러와 

json 안의 내용을 하나씩 하나씩 빼서 

사용하는 법을 보도록 하자.



Test.java


import java.io.FileReader;

import java.util.Iterator;


import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

import org.json.simple.parser.JSONParser;


public class Test {


    public static void main(String[] args) {

        

        

        JSONParser parser = new JSONParser();        


        try {

// D드라이브의 jsontest.json 파일 내용을 읽어 Object에 넣기.

            Object obj = parser.parse(new FileReader("d:\\jsontest.json"));            

           

// Object 화 된 내용을 JsonObject 로 캐스팅 

JSONObject jsonObj = (JSONObject)obj;

            

            // pageInfo 값 출력

            System.out.println("pageInfo :: " + jsonObj.get("pageInfo") );

            

            // posts 값 출력

            System.out.println("posts :: " + jsonObj.get("posts") );

            

// 두줄 띄우기

            System.out.println("\n \n");

            

// pageInfo 값의 개별 값을 출력하기 위해 pageInfo 값을 또다른

// JsonObject 변수에 넣기 (캐스팅)

            JSONObject subJsonObj = (JSONObject)jsonObj.get("pageInfo");

            

            // 새로운 JsonObject pageInfo에서 추출한 pageName 출력

            System.out.println("pageName :: " + subJsonObj.get("pageName") );

            

            // 새로운 JsonObject pageInfo에서 추출한 pagePicpoc 출력

            System.out.println("pagePicpoc :: " + subJsonObj.get("pagePicpoc") );

            

// 두줄 띄우기

            System.out.println("\n \n");                        

            


// 여기서 posts의 내부 값은 [ ] 형태의 배열이기에 아래 처럼 사용한다.


            // JSONArray Print            


            JSONArray jsonArr = (JSONArray)jsonObj.get("posts");

            JSONObject jsonItem = null; 

            for(int i=0; i<jsonArr.size(); i++){

                jsonItem = (JSONObject)jsonArr.get(i);

                System.out.println("post_id :: " +  jsonItem.get("post_id"));                

                System.out.println("picpoc  :: " +  jsonItem.get("picOfPersonWhoPosted"));

                System.out.println("name :: " +  jsonItem.get("nameOfPersonWhoPosted"));

                System.out.println("message :: " +  jsonItem.get("message"));                

            }           

            

        } catch (Exception e) {

            e.printStackTrace();

        }      

    }

}






참고 : 배열 내용을 빼올 때 아래와 같이 Iterator를 사용하는 방법도 있다.



String strJson = "{ \"items\": { \"item1\": \"value\", \"item2\": \"value\" } }";

Iterator<?> itors = strJson.keys();

while(itors.hasNext() ) {

    String key = (String)itors.next();

    if ( resobj.get(key) instanceof JSONObject ) {

        JSONObject jobj = new JSONObject(itors.get(key).toString());

        System.out.println("item1  :: " + jobj.getString("item1"));

        System.out.println("item2  :: " + xx.getString("item2"));

    }

}




첨부 파일의 내용과 포스팅의 내용은 포스팅 중 

설명을 달면서 달라졌을 수도 있으니 참고 하길..