1 /* 2 * Copyright (C) 2011 Google 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 * http://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.google.gson.extras.examples.rawcollections; 17 18 import java.util.ArrayList; 19 import java.util.Collection; 20 21 import com.google.gson.Gson; 22 import com.google.gson.JsonArray; 23 import com.google.gson.JsonParser; 24 25 public class RawCollectionsExample { 26 static class Event { 27 private String name; 28 private String source; Event(String name, String source)29 private Event(String name, String source) { 30 this.name = name; 31 this.source = source; 32 } 33 @Override toString()34 public String toString() { 35 return String.format("(name=%s, source=%s)", name, source); 36 } 37 } 38 39 @SuppressWarnings({ "unchecked", "rawtypes" }) main(String[] args)40 public static void main(String[] args) { 41 Gson gson = new Gson(); 42 Collection collection = new ArrayList(); 43 collection.add("hello"); 44 collection.add(5); 45 collection.add(new Event("GREETINGS", "guest")); 46 String json = gson.toJson(collection); 47 System.out.println("Using Gson.toJson() on a raw collection: " + json); 48 JsonArray array = JsonParser.parseString(json).getAsJsonArray(); 49 String message = gson.fromJson(array.get(0), String.class); 50 int number = gson.fromJson(array.get(1), int.class); 51 Event event = gson.fromJson(array.get(2), Event.class); 52 System.out.printf("Using Gson.fromJson() to get: %s, %d, %s", message, number, event); 53 } 54 } 55