AS Jackson編⑥解答~ObjectMapper(Jackson)を使う~APIレスポンス(複数の場合)をJSON形式で受け取り、それをログに通常表示する~
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ApiClient apiClient = new ApiClient();
try {
apiClient.doInSchedule("https://opendata.yamanashi.dev/api/onsen");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
activity_main.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:gravity="center_horizontal">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PUSH"
android:layout_marginTop="80sp"/>
</LinearLayout>
ApiClient.java
public class ApiClient {
void doInSchedule(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
String msg = e.getMessage();
Log.v("MY_LOG","メッセージ:"+msg);
}
@Override
public void onResponse(okhttp3.Call call, Response response) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String jsonText = response.body().string();
try {
JSONArray jsonArray = new JSONArray(jsonText);
int number = jsonArray.length();
Log.v("MY_LOG",Integer.toString(number));
Log.v("MY_LOG",jsonArray.toString());
Log.v("MY_LOG",jsonArray.get(3).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
AndroidManifest.xmlに、<manifest>タグ下に下記追加
<uses-permission android:name="android.permission.INTERNET"/>
build.gradle(Module)のdependenciesの中に下記追加
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.14.0'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.14.0'
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations
implementation group: 'com.fasterxml.jackson.core', name: 'jackson-annotations', version: '2.14.0'
implementation 'com.squareup.okhttp3:okhttp:3.4.2'