Develop/Android

[Android] Retrofit/Okhttp jsonplaceholder json 사용 + gson

안다희 2019. 1. 19. 13:19
728x90

꿀팁

https://march3samwuli.tistory.com/entry/Retrofit-2%EB%A1%9C-Http%ED%86%B5%EC%8B%A0-%EA%B5%AC%ED%98%84-%EC%8B%9C%EA%B0%84%EC%9D%84-%EB%8B%A8%EC%B6%95%ED%95%B4%EB%B3%B4%EC%9E%90



=======================================================================

음 내가 해본바로 gson으로 데이터를 개별적으로 갖고오고 싶다면.

예를 들어

{

    "isExist": false,

    "data": [

        {

            "isbn": "8990245575 9788990245571",

            "book_name": "긍정탐구(AI) 조직변화(사례위주의 알기 쉬운 실무 AI 가이드 북)",

            "author": [

                "Frank J Barrett",

                "Ronald E Fry"

            ],

            "contents": "『긍정탐구(AI) 조직변화』는 조직학습과 변화에 대한 간단하면서도 파격적인 철학을 제시한다. 즉, 인간 시스템의 협력역량에 생명력을 불어넣는 모든 것을 발견하고, 발산하라는 것이다.",

            "thumbnail": "https://search1.kakaocdn.net/thumb/R120x174.q85/?fname=http%3A%2F%2Ft1.daumcdn.net%2Flbook%2Fimage%2F1317696%3Ftimestamp%3D20190127193635"

        }

    ]

}


여기서 isExist만 갖고오고 싶다면

Call<IsExist> 이렇게 데이터모델 따로 만들어서 얘만 가져오면 됨.

IsExist 모델엔 Boolean isExist 하나만 있겠지.

=======================================================================


http://jsonplaceholder.typicode.com/comments/?postId=1 

여기서 데이터 가져올거임





0. build.gradle에 추가

 implementation 'com.squareup.retrofit2:retrofit:2.1.0'

implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'



1. ApiService 인터페이스 만들기

public interface ApiService {
public static final String API_URL = "http://jsonplaceholder.typicode.com/";

@GET("comments")
Call<ResponseBody>getComment(@Query("postId") int postId);

@POST("comments")
Call<ResponseBody>getPostComment(@Query("postId") int postId);

@GET("comments")
Call<ResponseBody>getComment(@Query("postId") String postId);

@FormUrlEncoded
@POST("comments")
Call<ResponseBody>getPostCommentStr(@Field("postId") int postId);

} 





2. NetworkManager 클래스 만들기

public class NetworkManager{

private static Retrofit retrofit;
private static ApiService apiService;

private static Retrofit buildRetrofit(){
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();


return new Retrofit.Builder()
.client(client)
.baseUrl(ApiService.API_URL).build();
}

private static Retrofit getRetrofit() {
if (retrofit==null){
retrofit = buildRetrofit();
}
return retrofit;
}


public static ApiService getApiService(){
if (apiService==null){
apiService = getRetrofit().create(ApiService.class);
}
return apiService;
}

} 



return new Retrofit.Builder()
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(ApiService.API_URL).build();

gson이면 저렇게!!


3. Data 클래스 만들기 (postId ~ body 저장하기 위한)

public class Data {
//json 파싱
int postId;
int id;
String name;
String email;
String body;

public String toString() {
String s = "";
s += postId + "/";
s += id + "/";
s += name + "/";
s += email + "/";
s += body + "/";
return s;
}

public int getPostId() {
return postId;
}

public void setPostId(int postId) {
this.postId = postId;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getBody() {
return body;
}

public void setBody(String body) {
this.body = body;
}

} 



4. MainActivity.java (데이터 파싱하고 싶은 액티비티)에 추가

Call<ResponseBody> comment = NetworkManager.getApiService().getComment(1);
comment.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String result = response.body().string();
Log.v("Test", result); //받아온 데이터
try {
JSONArray jsonArray = new JSONArray(result);
data = new Data();
for (int i = 0 ; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
data.setPostId(jsonObject.getInt("postId"));
data.setId(jsonObject.getInt("id"));
data.setName(jsonObject.getString("name"));
data.setEmail(jsonObject.getString("email"));
data.setBody(jsonObject.getString("body"));
//dataArrayList.add(data);
text.setText(data.toString());
Log.v("Test", jsonObject.toString());


}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {

}

}); 



5. activity_main.xml 에는 다음 textview가 있음. 여기에 데이터 파싱! (근데 위 코드는 맨 마지막 데이터만 텍스트에 표시된다..ㅎㅎ 이건 알아서 다시 고쳐보기!

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="40dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="오늘은 뭘 읽어볼까?"
android:textSize="35dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toBottomOf="@+id/btn_my" /> 







===========================

gson은 json과 다르게 ResponseBody를 안써도 되는듯?


gson이용하면!


0. build.gradle에 추가

implementation 'com.squareup.retrofit2:converter-gson:2.1.0'  //gson 추가한거임


implementation 'com.squareup.retrofit2:retrofit:2.1.0'

implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'


1. ApiService 인터페이스 만들기

public interface BookApiService {
/**
* 모든 API
* accessToken, idToken, refreshToken
* 필드를 추가해사 보내주세요!!
*/

// @FormUrlEncoded
// @GET("tags")
// Call<ResponseBody> getTags(@Field("accessToken") String accessToken,
// @Field("idToken") String idToken,
// @Field("refreshToken") String refreshToken);

@GET("tags/")
Call<List<Tag>> getTags(); //아까랑 다른점은 ResponseBody가 아니라 List<Tag> 라는 점!

} 



2. NetworkManager 클래스 만들기

package org.techtown.just.network;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class NetworkManager {

private static final String API_URL = "https://82uym5oh19.execute-api.ap-northeast-2.amazonaws.com/dev/";
private static Retrofit retrofit;
private static LoginApiService apiServiceLogin;
private static BookApiService bookApiService;


private static Retrofit buildRetrofit() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();


return new Retrofit.Builder()
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(API_URL).build();
}

private static Retrofit getRetrofit() {
if (retrofit == null) {
retrofit = buildRetrofit();
}
return retrofit;
}


public static LoginApiService getLoginApi() {
if (apiServiceLogin == null) {
apiServiceLogin = getRetrofit().create(LoginApiService.class);
}
return apiServiceLogin;
}

public static BookApiService getBookApi() {
if (bookApiService == null) {
bookApiService = getRetrofit().create(BookApiService.class);
}
return bookApiService;
}

} 

빨간글씨가 추가됨.


3. Tag 클래스 추가

package org.techtown.just.model;

public class Tag {
int tag_id;
String tag_name;

@Override
public String toString() {
return tag_id + " : " + tag_name;
}

public int getTag_id() {
return tag_id;
}

public void setTag_id(int tag_id) {
this.tag_id = tag_id;
}

public String getTag_name() {
return tag_name;
}

public void setTag_name(String tag_name) {
this.tag_name = tag_name;
}

} 



4. TagsActivity.java (데이터 파싱하고 싶은 액티비티)에 추가

package org.techtown.just;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.techtown.just.model.Post;
import org.techtown.just.model.Tag;
import org.techtown.just.network.NetworkManager;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TagsActivity extends AppCompatActivity {

@BindView(R.id.text)
TextView text;

Tag tag;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tags);
ButterKnife.bind(this);

Call<List<Tag>> list = NetworkManager.getBookApi().getTags();
list.enqueue(new Callback<List<Tag>>() {
@Override
public void onResponse(Call<List<Tag>> call, Response<List<Tag>> response) {
List<Tag> tags = response.body();
text.setText(tags.get(2).toString());
}

@Override
public void onFailure(Call<List<Tag>> call, Throwable t) {
Toast.makeText(TagsActivity.this, "오류가 발생했습니다.", Toast.LENGTH_SHORT).show();
}
});
}

} 


출처: https://mingos-habitat.tistory.com/34 [밍고의서식지:티스토리]