본문으로 바로가기

[안드로이드]JSON파싱(json parser)

category Android 2017. 9. 4. 11:13

안녕하세요.


오랜만에 글쓰게 되었습니다.


8.31일 부터 제4회 대한민국 해카톤 대회에 나간다고 많이 못썻어요.


대신 대회에서 우수상을 받았습니다.


오늘은 안드로이드에서 공공기관이나 여러 기관에서 공개된 api 를 사용할때 파싱이라는 것을 해야 하는데요.


파싱에는 대표적으로 xml, json 등이 있습니다.


오늘은 json 파싱에 대해 알아 볼건데요.


기본적으로 json은 [](대괄호) 와 {}(중괄호) 로 나뉘어 있는데요.


{"food_list":[{"code":"F3J01","seq_code":102,"food_name":"32도 숙성 양조진간장"}]} 


이런 데이터가 있다고 가정합시다. (데이터스토어의 식품api중 일부입니다.)


[]대괄호는 JSONArray 를 이용하여 구별하고 {}중괄호는 JSONObject 를 이용하여 구별합니다.


정확한 사용법을 알아 보겠습니다.


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView)findViewById(R.id.parsetext);
        String resultText = "값이없음";

        try {
            resultText = new Task().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        textView.setText(resultText);
    }
}

메인 액티비티 입니다.


api를 통신을 통해 가져오기위해 AsyncTask 를 사용합니다.


<uses-permission android:name="android.permission.INTERNET" />


통신을 하기위해서는 기본적으로 인터넷 퍼미션을 열어줘야합니다.


public class Task extends AsyncTask<string, void, string> {

    String clientKey = "#########################";;
    private String str, receiveMsg;
    private final String ID = "########";

    @Override
    protected String doInBackground(String... params) {
        URL url = null;
        try {
            url = new URL("http://api.dbstore.or.kr:8880/foodinfo/list.do?uid="+ID+"&n=10&p=1&c=F3J01&s=food_name&o=u");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestProperty("x-waple-authorization", clientKey);

            if (conn.getResponseCode() == conn.HTTP_OK) {
                InputStreamReader tmp = new InputStreamReader(conn.getInputStream(), "UTF-8");
                BufferedReader reader = new BufferedReader(tmp);
                StringBuffer buffer = new StringBuffer();
                while ((str = reader.readLine()) != null) {
                    buffer.append(str);
                }
                receiveMsg = buffer.toString();
                Log.i("receiveMsg : ", receiveMsg);

                reader.close();
            } else {
                Log.i("통신 결과", conn.getResponseCode() + "에러");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return receiveMsg;
    }
}


json 값을 받아오기위한 Task 클래스입니다. (이번 예제는 데이터스토어의 api를 이용하였습니다.)


이렇게 json 값을 받아오면 

{"food_list":[{"code":"F3J01","seq_code":102,"food_name":"32도 숙성 양조진간장","thumb_img":"http://api.eatsight.com/FoodData/client_thumb/F3J01102_TOP.jpg","sell_com":"씨제이제일제당(주)","barcode":"8801007081496","volume":"940 ml","food_type":"양조간장","ing_first":""},{"code":"F3J01","seq_code":19,"food_name":"32도숙성 양조간장","thumb_img":"http://api.eatsight.com/FoodData/client_thumb/F3J0119_TOP.jpg","sell_com":"씨제이제일제당(주)","barcode":"8801007081441","volume":"1.6L","food_type":"양조간장","ing_first":""}...


이런식으로 값을 받아옵니다.


이런 데이터를 우리는 파싱을 통해 필요한 데이터만 가공하여 사용할건데요.

public String[] foodlistjsonParser(String jsonString) {

        String seq_code = null;
        String food_name = null;
        String code = null;
        String kcal = null;
        String sell_com = null;
        String thumb_img = null;
        String food_type = null;
        String barcode = null;
        String volume = null;

        String[] arraysum = new String[8];
        try {
            JSONArray jarray = new JSONObject(jsonString).getJSONArray("food_list");
            for (int i = 0; i < jarray.length(); i++) {
                HashMap map = new HashMap<>();
                JSONObject jObject = jarray.getJSONObject(i);

                code = jObject.optString("code");
                seq_code = jObject.optString("seq_code");
                food_name = jObject.optString("food_name");
                thumb_img = jObject.optString("thumb_img");
                sell_com = jObject.optString("sell_com");
                barcode = jObject.optString("barcode");
                volume = jObject.optString("volume");
                food_type = jObject.optString("food_type");

                arraysum[0] = code;
                arraysum[1] = seq_code;
                arraysum[2] = food_name;
                arraysum[3] = thumb_img;
                arraysum[4] = sell_com;
                arraysum[5] = barcode;
                arraysum[6] = volume;
                arraysum[7] = food_type;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return arraysum;
    }
 


Task 의 결과로 얻어진 가공되지 않은 값을을 jsonparser 메소드로 넘겨준뒤 가공을 합니다.


메소드 안에서는 JSONArray 로 {"food_list":[{"code":"F3J01","seq_code":102,"food_name":"32도 숙성 양조진간장"}]} 


[] 앞의 food_list로 []를 구별한뒤


[]안의 값들을 JSONObject 로 {} 안의 값들을 태그별로 나누는 작업을 합니다. (태그는 "code":"F3J01","seq_code":102 중 code, seq_code )



가공을 하게되면 이렇게 태그별로 나눠진 값을 알 수 있습니다.