Java Code Examples for com.squareup.moshi.Moshi#adapter()
The following examples show how to use
com.squareup.moshi.Moshi#adapter() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PolymorphicJsonAdapterFactoryTest.java From moshi with Apache License 2.0 | 6 votes |
@Test public void nonObjectDoesNotConsume() throws IOException { Moshi moshi = new Moshi.Builder() .add(PolymorphicJsonAdapterFactory.of(Message.class, "type") .withSubtype(Success.class, "success") .withSubtype(Error.class, "error")) .build(); JsonAdapter<Message> adapter = moshi.adapter(Message.class); JsonReader reader = JsonReader.of(new Buffer().writeUtf8("\"Failure\"")); try { adapter.fromJson(reader); fail(); } catch (JsonDataException expected) { assertThat(expected).hasMessage("Expected BEGIN_OBJECT but was STRING at path $"); } assertThat(reader.nextString()).isEqualTo("Failure"); assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); }
Example 2
Source File: FromJsonWithoutStrings.java From moshi with Apache License 2.0 | 6 votes |
public void run() throws Exception { // For some reason our JSON has date and time as separate fields. We will clean that up during // parsing: Moshi will first parse the JSON directly to an EventJson and from that the // EventJsonAdapter will create the actual Event. String json = "" + "{\n" + " \"title\": \"Blackjack tournament\",\n" + " \"begin_date\": \"20151010\",\n" + " \"begin_time\": \"17:04\"\n" + "}\n"; Moshi moshi = new Moshi.Builder().add(new EventJsonAdapter()).build(); JsonAdapter<Event> jsonAdapter = moshi.adapter(Event.class); Event event = jsonAdapter.fromJson(json); System.out.println(event); System.out.println(jsonAdapter.toJson(event)); }
Example 3
Source File: PolymorphicJsonAdapterFactoryTest.java From moshi with Apache License 2.0 | 6 votes |
@Test public void unregisteredSubtype() { Moshi moshi = new Moshi.Builder() .add(PolymorphicJsonAdapterFactory.of(Message.class, "type") .withSubtype(Success.class, "success") .withSubtype(Error.class, "error")) .build(); JsonAdapter<Message> adapter = moshi.adapter(Message.class); try { adapter.toJson(new EmptyMessage()); } catch (IllegalArgumentException expected) { assertThat(expected).hasMessage("Expected one of [class" + " com.squareup.moshi.adapters.PolymorphicJsonAdapterFactoryTest$Success, class" + " com.squareup.moshi.adapters.PolymorphicJsonAdapterFactoryTest$Error] but found" + " EmptyMessage, a class" + " com.squareup.moshi.adapters.PolymorphicJsonAdapterFactoryTest$EmptyMessage. Register" + " this subtype."); } }
Example 4
Source File: ReadJson.java From moshi with Apache License 2.0 | 6 votes |
public void run() throws Exception { String json = "" + "{\n" + " \"hidden_card\": {\n" + " \"rank\": \"6\",\n" + " \"suit\": \"SPADES\"\n" + " },\n" + " \"visible_cards\": [\n" + " {\n" + " \"rank\": \"4\",\n" + " \"suit\": \"CLUBS\"\n" + " },\n" + " {\n" + " \"rank\": \"A\",\n" + " \"suit\": \"HEARTS\"\n" + " }\n" + " ]\n" + "}\n"; Moshi moshi = new Moshi.Builder().build(); JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class); BlackjackHand blackjackHand = jsonAdapter.fromJson(json); System.out.println(blackjackHand); }
Example 5
Source File: PolymorphicJsonAdapterFactoryTest.java From moshi with Apache License 2.0 | 6 votes |
@Test public void nonUniqueSubtypes() throws IOException { Moshi moshi = new Moshi.Builder() .add(PolymorphicJsonAdapterFactory.of(Message.class, "type") .withSubtype(Success.class, "success") .withSubtype(Success.class, "data") .withSubtype(Error.class, "error")) .build(); JsonAdapter<Message> adapter = moshi.adapter(Message.class); assertThat(adapter.fromJson("{\"type\":\"success\",\"value\":\"Okay!\"}")) .isEqualTo(new Success("Okay!")); assertThat(adapter.fromJson("{\"type\":\"data\",\"value\":\"Data!\"}")) .isEqualTo(new Success("Data!")); assertThat(adapter.fromJson("{\"type\":\"error\",\"error_logs\":{\"order\":66}}")) .isEqualTo(new Error(Collections.<String, Object>singletonMap("order", 66d))); assertThat(adapter.toJson(new Success("Data!"))) .isEqualTo("{\"type\":\"success\",\"value\":\"Data!\"}"); }
Example 6
Source File: PolymorphicJsonAdapterFactoryTest.java From moshi with Apache License 2.0 | 6 votes |
@Test public void unregisteredLabelValue() throws IOException { Moshi moshi = new Moshi.Builder() .add(PolymorphicJsonAdapterFactory.of(Message.class, "type") .withSubtype(Success.class, "success") .withSubtype(Error.class, "error")) .build(); JsonAdapter<Message> adapter = moshi.adapter(Message.class); JsonReader reader = JsonReader.of(new Buffer().writeUtf8("{\"type\":\"data\",\"value\":\"Okay!\"}")); try { adapter.fromJson(reader); fail(); } catch (JsonDataException expected) { assertThat(expected).hasMessage("Expected one of [success, error] for key 'type' but found" + " 'data'. Register a subtype for this label."); } assertThat(reader.peek()).isEqualTo(JsonReader.Token.BEGIN_OBJECT); }
Example 7
Source File: ComplexAdapterUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenDeserializing_thenCorrectJsonConsumed() throws IOException { Moshi moshi = new Moshi.Builder() .add(new JsonDateTimeAdapter()) .build(); JsonAdapter<ZonedDateTime> jsonAdapter = moshi.adapter(ZonedDateTime.class); String json = "{\"date\":\"2020-02-17\",\"time\":\"07:53:27.064\",\"timezone\":\"Europe/London\"}"; ZonedDateTime now = jsonAdapter.fromJson(json); System.out.println(now); }
Example 8
Source File: RecoverFromTypeMismatch.java From moshi with Apache License 2.0 | 5 votes |
public void run() throws Exception { String json = "[\"DIAMONDS\", \"STARS\", \"HEARTS\"]"; Moshi moshi = new Moshi.Builder() .add(DefaultOnDataMismatchAdapter.newFactory(Suit.class, Suit.CLUBS)) .build(); JsonAdapter<List<Suit>> jsonAdapter = moshi.adapter( Types.newParameterizedType(List.class, Suit.class)); List<Suit> suits = jsonAdapter.fromJson(json); System.out.println(suits); }
Example 9
Source File: RenameUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenSerializing_thenFieldsGetRenamed() { Moshi moshi = new Moshi.Builder() .build(); JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class); Post post = new Post("My Post", "Baeldung"); String json = jsonAdapter.toJson(post); System.out.println(json); }
Example 10
Source File: PolymorphicJsonAdapterFactoryTest.java From moshi with Apache License 2.0 | 5 votes |
/** * Longs that do not have an exact double representation are problematic for JSON. It is a bad * idea to use JSON for these values! But Moshi tries to retain long precision where possible. */ @Test public void unportableTypes() throws IOException { Moshi moshi = new Moshi.Builder() .add(PolymorphicJsonAdapterFactory.of(Message.class, "type") .withSubtype(MessageWithUnportableTypes.class, "unportable")) .build(); JsonAdapter<Message> adapter = moshi.adapter(Message.class); assertThat(adapter.toJson(new MessageWithUnportableTypes(9007199254740993L))) .isEqualTo("{\"type\":\"unportable\",\"long_value\":9007199254740993}"); MessageWithUnportableTypes decoded = (MessageWithUnportableTypes) adapter.fromJson( "{\"type\":\"unportable\",\"long_value\":9007199254740993}"); assertThat(decoded.long_value).isEqualTo(9007199254740993L); }
Example 11
Source File: CustomAdapterWithDelegate.java From moshi with Apache License 2.0 | 5 votes |
public void run() throws Exception { // We want to match any Stage that starts with 'in-progress' as Stage.IN_PROGRESS // and leave the rest of the enum values as to match as normal. Moshi moshi = new Moshi.Builder().add(new StageAdapter()).build(); JsonAdapter<Stage> jsonAdapter = moshi.adapter(Stage.class); System.out.println(jsonAdapter.fromJson("\"not-started\"")); System.out.println(jsonAdapter.fromJson("\"in-progress\"")); System.out.println(jsonAdapter.fromJson("\"in-progress-step1\"")); }
Example 12
Source File: PolymorphicJsonAdapterFactoryTest.java From moshi with Apache License 2.0 | 5 votes |
@Test public void nonStringLabelValue() throws IOException { Moshi moshi = new Moshi.Builder() .add(PolymorphicJsonAdapterFactory.of(Message.class, "type") .withSubtype(Success.class, "success") .withSubtype(Error.class, "error")) .build(); JsonAdapter<Message> adapter = moshi.adapter(Message.class); try { adapter.fromJson("{\"type\":{},\"value\":\"Okay!\"}"); fail(); } catch (JsonDataException expected) { assertThat(expected).hasMessage("Expected a string but was BEGIN_OBJECT at path $.type"); } }
Example 13
Source File: AlternativeAdapterUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenSerializing_thenAlternativeAdapterUsed() { Moshi moshi = new Moshi.Builder() .add(new EpochMillisAdapter()) .build(); JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class); String json = jsonAdapter.toJson(new Post("Introduction to Moshi Json", "Baeldung", Instant.now())); System.out.println(json); }
Example 14
Source File: RenameUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void whenSerializing_thenRenamedFieldsGetConsumed() throws IOException { Moshi moshi = new Moshi.Builder() .build(); JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class); String json = "{\"authored_by\":\"Baeldung\",\"title\":\"My Post\"}"; Post post = jsonAdapter.fromJson(json); System.out.println(post); }
Example 15
Source File: PolymorphicJsonAdapterFactoryTest.java From moshi with Apache License 2.0 | 5 votes |
@Test public void nullSafe() throws IOException { Moshi moshi = new Moshi.Builder() .add(PolymorphicJsonAdapterFactory.of(Message.class, "type") .withSubtype(Success.class, "success") .withSubtype(Error.class, "error")) .build(); JsonAdapter<Message> adapter = moshi.adapter(Message.class); JsonReader reader = JsonReader.of(new Buffer().writeUtf8("null")); assertThat(adapter.fromJson(reader)).isNull(); assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); }
Example 16
Source File: Main.java From SaliensAuto with GNU General Public License v3.0 | 5 votes |
public static Planets getPlanets(){ String res = RequestUtils.get( "GetPlanets", "active_only=1" ).data; Moshi moshi = new Moshi.Builder().build(); JsonAdapter<PlanetsResponse> jsonAdapter = moshi.adapter(PlanetsResponse.class); try { PlanetsResponse planets = jsonAdapter.fromJson(res); if(planets==null || planets.response==null || planets.response.planets==null || planets.response.planets.size()==0) return null; return planets.response; } catch (IOException e) { e.printStackTrace(); } return null; }
Example 17
Source File: Main.java From SaliensAuto with GNU General Public License v3.0 | 5 votes |
public static Planet getPlanetData(String id){ String data = RequestUtils.get("GetPlanet","id="+id).data; Moshi moshi = new Moshi.Builder().build(); JsonAdapter<PlanetsResponse> jsonAdapter = moshi.adapter(PlanetsResponse.class); try { PlanetsResponse response = jsonAdapter.fromJson(data); if(response==null || response.response==null || response.response.planets==null || response.response.planets.size()==0) return null; return response.response.planets.get(0); } catch (IOException e) { e.printStackTrace(); } return null; }
Example 18
Source File: PolymorphicJsonAdapterFactoryTest.java From moshi with Apache License 2.0 | 5 votes |
@Test public void fromJson() throws IOException { Moshi moshi = new Moshi.Builder() .add(PolymorphicJsonAdapterFactory.of(Message.class, "type") .withSubtype(Success.class, "success") .withSubtype(Error.class, "error")) .build(); JsonAdapter<Message> adapter = moshi.adapter(Message.class); assertThat(adapter.fromJson("{\"type\":\"success\",\"value\":\"Okay!\"}")) .isEqualTo(new Success("Okay!")); assertThat(adapter.fromJson("{\"type\":\"error\",\"error_logs\":{\"order\":66}}")) .isEqualTo(new Error(Collections.<String, Object>singletonMap("order", 66d))); }
Example 19
Source File: Unwrap.java From moshi with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { String json = "" + "{\"data\":" + " {\n" + " \"rank\": \"4\",\n" + " \"suit\": \"CLUBS\"\n" + " }" + "}"; Moshi moshi = new Moshi.Builder().add(EnvelopeJsonAdapter.FACTORY).build(); JsonAdapter<Card> adapter = moshi.adapter(Card.class, Enveloped.class); Card out = adapter.fromJson(json); System.out.println(out); }
Example 20
Source File: ResourceIdentifier.java From moshi-jsonapi with MIT License | 4 votes |
public Adapter(Moshi moshi) { jsonBufferJsonAdapter = moshi.adapter(JsonBuffer.class); }