LoginSignup
3
0

More than 5 years have passed since last update.

Moshiを使ってPOJOからJsonObjectとJsonArrayを作成する

Last updated at Posted at 2016-07-21

前提

POJO

public class User {
  @Json(name = "name")
  String name;
  @Json(name = "age")
  int age;

  public User(String name, int age) {
    this.name = name;
    this.age = age;
  }  
}

POJOからJsonObjectを作成する

code

import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;

String json = new Moshi.Builder().build().adapter(User.class).toJson(new User("hoge", 10));

json

{"age":10,"name":"hoge"}

POJOからJsonArrayを作成する

code

import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import java.lang.reflect.Type;


List<User> users = new ArrayList<User>();
users.add(new User("hoge", 10));

Type listOfUsersType = Types.newParameterizedType(List.class, User.class);

String json = new Moshi.Builder().build().adapter(listOfUsersType).toJson(users);

json

[{"age":10,"name":"hoge"}]

わんらいなー

new Moshi.Builder().build().adapter(Types.newParameterizedType(List.class, User.class)).toJson(Observable.just(new User("hoge", 10)).toList().toBlocking().single());
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0