[Android] JSON Parser Android 2012. 3. 8. 16:54

JSON은 XML 보다 좀 더 간략화 된 데이터의 구성이다. 이는 단순한 유니코드 텍스트 파일로 가독성이 좀 떨어지나 어느 환경이든 적용이 가능하다.

또한 파서 자체가 라이브러리 형태로 제공되어 직접 문자열을 파싱 할 필요가 없다.

JSON에 저장되는 정보 형태는 배열과 객체, 단순 값으로 된다.

다음 코드는 배열과 객체를 파싱하여 이용하는 코드 이다.

먼저 배열의 경우이다.

public class ImageViewActivity extends Activity {
 EditText edit;

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  Button call = (Button) findViewById(R.id.call);
  edit = (EditText) findViewById(R.id.edit);
  call.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v) {
    String str = "[1,2,3,4,5]";
    try{
     int sum=0;
     JSONArray ja = new JSONArray(str);
     for(int i=0;i<ja.length();i++){
      sum+=ja.getInt(i);
     }
     edit.setText("total" + sum);
    }
    catch(JSONException ex){
     Toast.makeText(v.getContext(), ex.getMessage(), 0).show();
    }
   }
  });
 }
}

위에서 봤듯 Array에 넣어 해당하는 타입으로 가져와 데이터를 조작 할 수가 있다. 다음은 객체형이다.

onClick 내의 내용을 다음과 같이 바꾸기만 하면 된다.

String str = "[{\"one1\":\"1\", \"one2\":\"11\", \"one3\":\"111\"},{\"one1\":\"2\", \"one2\":\"22\", \"one3\":\"222\"}]";
    String temp = "";
    try{
     JSONArray ja = new JSONArray(str);
     for(int i=0;i<ja.length();i++){
      JSONObject obj = ja.getJSONObject(i);
      temp += obj.getString("one1")+obj.getString("one2")+obj.getString("one3")+"\n";
     }
     edit.setText(temp);
    }
    catch(JSONException ex){
     Toast.makeText(v.getContext(), ex.getMessage(), 0).show();
    }

객체형은 getJSONObject에서 가져와 각기 데이터를 추출한다. 여기에서 배열 형태로 저장된 규칙을 잘 지키기만 하면 된다.