728x90

JSON

 

JSON 이란

 

  • JavaScript Object Notation라는 의미의 축약어로 데이터를 저장하거나 전송할 때 많이 사용되는 경량의 DATA 교환 형식이다.

서버로부터 데이터를 가져오기 위해서 하나의 약속으로 JSON이란 데이터형식을 사용하여 통신한다고 생각하면된다.

 

JSON데이터는 하나의 NAME과 VALUE로 이루어져있다.

 

 

데이터이름(NAME)에는 String타입이 오며

 

값(value)에는 숫자, 문자열, 불리언(boolean), 객체, 배열(array), NULL값등이 올수있다.

 

 

 

 

JSON 배열

 

JSON배열은 중괄호{}가 아닌 대괄호[]로 둘러쌓아 표현한다.

JSON배열은 쉼표 , 를 사용하여 여러 JSON 데이터를 포함할수있다.

 

<안드로이드에서 JSON 다루기>

 

 

<MainActivity.java>

package com.example.jsonpr01;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    private TextView textView;
    String test =
            "[{'name':'배트맨','age':37,'address':'고담'},"+
                    "{'name':'슈퍼맨','age':36,'address':'뉴욕'},"+
                    "{'name':'앤트맨','age':28,'address':'LA'}]";

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

        textView = findViewById(R.id.textView);

        try{
            parse();
        }catch (Exception e){

        }

    }

    public void parse() throws Exception{

        StringBuffer sb = new StringBuffer();

        try{
            JSONArray jarray = new JSONArray(test);

            for(int i = 0; i< jarray.length(); i++)
            {
                JSONObject jsonObject = jarray.getJSONObject(i);
                String address = jsonObject.getString("address");
                String name = jsonObject.getString("name");
                int age = jsonObject.getInt("age");

                sb.append("주소:" + address
                        + "이름:" + name
                        + "나이:" + age + "\n");
            }
            textView.setText(sb.toString());
        }catch (JSONException e){
            e.printStackTrace();
        }
    }
}

<activity_main.xml>

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

String test를 JSON형태로 저장한 후

 

JSONArray jarray = new JSONArray(test)  //test는 json  json배열 생성

 

반복문을통해 0부터 jarray.length까지 반복해준다.

{

JSONObject jsonObjtect = jarray.getJSONObject(i)     // jsonObject를 생성해주고

String address = jsonObject.getString("address"); // json에서 name이 address의 값을 가져옴

String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");

 

sb.append("주소:" + address
+ "이름:" + name
+ "나이:" + age + "\n");

//가져온값들을 sb (sb는 StringBuffer)에 더해준다.

}

 

이렇게 더해준값들을 

textView.setText(sb.toString())을 통해 확인한다.

 

728x90

+ Recent posts