Skip to content

Instantly share code, notes, and snippets.

@kamikat
Last active March 6, 2018 00:17
Show Gist options
  • Save kamikat/24b08d3bfcb7ce964dd999c49a13ccaf to your computer and use it in GitHub Desktop.
Save kamikat/24b08d3bfcb7ce964dd999c49a13ccaf to your computer and use it in GitHub Desktop.
polymorphic parsing example of moshi-jsonapi
package moe.banana.jsonapi2.issue5;
import moe.banana.jsonapi2.JsonApi;
import moe.banana.jsonapi2.Resource;
@JsonApi(type = "accessToken") // `access-tokens` is recommended by JSON API specification
public class AccessToken extends Resource {
public String tokenType;
public String value;
}
package moe.banana.jsonapi2.issue5;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import moe.banana.jsonapi2.Resource;
import moe.banana.jsonapi2.ResourceAdapterFactory;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
public class PolymorphicTest {
public static final String JSON = "{" +
" \"jsonapi\": {" +
" \"version\": \"1.0\"" +
" }," +
" \"meta\": {" +
" \"isNew\": true" +
" }," +
" \"data\": [" +
" {" +
" \"id\": 4," +
" \"type\": \"user\"," +
" \"attributes\": {" +
" \"facebookId\": \"facebookId\"," +
" \"email\": \"[email protected]\"," +
" \"name\": \"Lê Uyên Nguyễn\"," +
" \"avatar\": \"users/avatars/8c0f5fc9e15003b1692d564b5a009b00.jpg\"," +
" \"updated_at\": \"2016-08-22 23:30:11\"," +
" \"created_at\": \"2016-08-22 23:30:11\"," +
" \"loc\": null" +
" }" +
" }," +
" {" +
" \"id\": \"cfc60085d96d2bdb46ac719586fe8e28\"," +
" \"type\": \"accessToken\"," +
" \"attributes\": {" +
" \"tokenType\": \"Bearer\"," +
" \"value\": \"token-abc\"" +
" }" +
" }" +
" ]" +
"}";
@Test
public void deserialization() throws Exception {
Moshi moshi = new Moshi.Builder()
.add(ResourceAdapterFactory.builder()
.add(AccessToken.class)
.add(User.class)
.build()).build();
Resource[] data = moshi.adapter(Resource[].class).fromJson(JSON);
assertThat(data[0], instanceOf(User.class));
assertThat(data[1], instanceOf(AccessToken.class));
}
}
package moe.banana.jsonapi2.issue5;
import moe.banana.jsonapi2.JsonApi;
import moe.banana.jsonapi2.Resource;
@JsonApi(type = "user") // `users` is recommended by JSON API specification
public class User extends Resource {
public String facebookId;
public String email;
public String name;
public String avatar;
public String updated_at;
public String created_at;
public String loc;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment