Android
Android] JSON 생성 및 파싱
김코식
2022. 3. 20. 17:36
JSON 생성하기
JSON파일을 담기 위한 폴더 생성
JSON파일을 구분하기 위해 Assets 폴더 하위에 Directiory 폴더 생성
폴더 생성 후 파일 생성
xml파일
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="값 불러오기"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="값"
android:id="@+id/text"
/>
</LinearLayout>
java 파일
package com.example.json_ex;
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AssetManager assetManager = getAssets();//assets 폴더 파일 가져오기
try{
InputStream is = assetManager.open("json/json");
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
StringBuffer buffer = new StringBuffer();
String line = reader.readLine();
while(line!=null){
buffer.append(line+"\n");
line = reader.readLine();
}
String jsonData = buffer.toString();
JSONObject jsonObject = new JSONObject(jsonData);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
textView.setText("이름"+name+"\n"+"나이"+age);
}
catch (IOException | JSONException e){e.printStackTrace();}
}
});
}
}
실행 화면
버튼 클릭시