1 /* 2 * Copyright (C) 2015 Square, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.squareup.moshi.recipes; 17 18 import com.squareup.moshi.FromJson; 19 import com.squareup.moshi.JsonAdapter; 20 import com.squareup.moshi.Moshi; 21 import com.squareup.moshi.ToJson; 22 23 public final class FromJsonWithoutStrings { run()24 public void run() throws Exception { 25 // For some reason our JSON has date and time as separate fields. We will clean that up during 26 // parsing: Moshi will first parse the JSON directly to an EventJson and from that the 27 // EventJsonAdapter will create the actual Event. 28 String json = 29 "" 30 + "{\n" 31 + " \"title\": \"Blackjack tournament\",\n" 32 + " \"begin_date\": \"20151010\",\n" 33 + " \"begin_time\": \"17:04\"\n" 34 + "}\n"; 35 36 Moshi moshi = new Moshi.Builder().add(new EventJsonAdapter()).build(); 37 JsonAdapter<Event> jsonAdapter = moshi.adapter(Event.class); 38 39 Event event = jsonAdapter.fromJson(json); 40 System.out.println(event); 41 System.out.println(jsonAdapter.toJson(event)); 42 } 43 main(String[] args)44 public static void main(String[] args) throws Exception { 45 new FromJsonWithoutStrings().run(); 46 } 47 48 private static final class EventJson { 49 String title; 50 String begin_date; 51 String begin_time; 52 } 53 54 public static final class Event { 55 String title; 56 String beginDateAndTime; 57 58 @Override toString()59 public String toString() { 60 return "Event{" 61 + "title='" 62 + title 63 + '\'' 64 + ", beginDateAndTime='" 65 + beginDateAndTime 66 + '\'' 67 + '}'; 68 } 69 } 70 71 private static final class EventJsonAdapter { 72 @FromJson eventFromJson(EventJson eventJson)73 Event eventFromJson(EventJson eventJson) { 74 Event event = new Event(); 75 event.title = eventJson.title; 76 event.beginDateAndTime = eventJson.begin_date + " " + eventJson.begin_time; 77 return event; 78 } 79 80 @ToJson eventToJson(Event event)81 EventJson eventToJson(Event event) { 82 EventJson json = new EventJson(); 83 json.title = event.title; 84 json.begin_date = event.beginDateAndTime.substring(0, 8); 85 json.begin_time = event.beginDateAndTime.substring(9, 14); 86 return json; 87 } 88 } 89 } 90