Created
April 6, 2016 10:18
-
-
Save kotucz/24d3932e87d5aa41363fbb12dccef9ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package moshi; | |
import android.test.AndroidTestCase; | |
import com.squareup.moshi.FromJson; | |
import com.squareup.moshi.JsonAdapter; | |
import com.squareup.moshi.Moshi; | |
import com.squareup.moshi.ToJson; | |
import com.squareup.moshi.Types; | |
import java.io.IOException; | |
import java.lang.reflect.Type; | |
public class MoshiParametrizedTypeAndroidTest extends AndroidTestCase { | |
public void testParametrizedType_fromJson() throws IOException { | |
final JsonAdapter<RulesList<Rule>> moshiAdapter = jsonAdapter(); | |
final RulesList<Rule> rulesList = moshiAdapter.fromJson("{\"serializedName\":\"FOO\"}"); | |
assertEquals("FOO", rulesList.item.name); | |
} | |
public void testParametrizedType_toJson() throws IOException { | |
final JsonAdapter<RulesList<Rule>> moshiAdapter = jsonAdapter(); | |
final RulesList<Rule> rulesList = new RulesList<>(); | |
rulesList.item.name = "BAR"; | |
final String json = moshiAdapter.toJson(rulesList); | |
assertEquals("{\"serializedName\":\"BAR\"}", json); | |
} | |
JsonAdapter<RulesList<Rule>> jsonAdapter() { | |
final Moshi moshi = new Moshi.Builder().add(new RulesListAdapter()).build(); | |
final Type type = Types.newParameterizedType(RulesList.class, Rule.class); | |
return moshi.adapter(type); | |
} | |
static class RulesListAdapter { | |
@FromJson | |
RulesList<Rule> fromJson(RuleJson jsonRules) { | |
final RulesList<Rule> rulesList = new RulesList<>(); | |
rulesList.item.name = jsonRules.serializedName; | |
return rulesList; | |
} | |
@ToJson | |
RuleJson toJson(RulesList<Rule> rulesList) { | |
final RuleJson ruleJson = new RuleJson(); | |
ruleJson.serializedName = rulesList.item.name; | |
return ruleJson; | |
} | |
} | |
// domain model - not json | |
static class RulesList<T> { | |
Rule item = new Rule(); | |
} | |
// domain model - not json | |
static class Rule { | |
String name; | |
} | |
// serialized json format | |
static class RuleJson { | |
String serializedName; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Android test failing with: