Skip to content

Instantly share code, notes, and snippets.

@shts
Last active July 21, 2016 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shts/58464c537e07d89ab50fe8e8f9f3d821 to your computer and use it in GitHub Desktop.
Save shts/58464c537e07d89ab50fe8e8f9f3d821 to your computer and use it in GitHub Desktop.
Moshiを使ってPOJOからJsonObjectとJsonArrayを作成する ref: http://qiita.com/shts/items/83d261c7666ab0069326
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;
}
}
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
String json = new Moshi.Builder().build().adapter(User.class).toJson(new User("hoge", 10));
{"age":10,"name":"hoge"}
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);
[{"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());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment