gson-comments/gson/src/test/java/com/google/gson/functional/DefaultTypeAdaptersTest.java

532 lines
18 KiB
Java
Raw Normal View History

2008-09-01 05:13:32 +02:00
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gson.functional;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
2008-09-01 05:13:32 +02:00
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URI;
import java.net.URL;
import java.sql.Time;
import java.sql.Timestamp;
2008-09-01 05:13:32 +02:00
import java.text.DateFormat;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
2008-09-01 05:13:32 +02:00
import java.util.Date;
import java.util.GregorianCalendar;
2008-09-01 05:13:32 +02:00
import java.util.HashSet;
import java.util.List;
2008-09-01 05:13:32 +02:00
import java.util.Locale;
2008-12-31 01:43:40 +01:00
import java.util.Properties;
2008-09-01 05:13:32 +02:00
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.UUID;
import junit.framework.TestCase;
2008-09-01 05:13:32 +02:00
/**
* Functional test for Json serialization and deserialization for common classes for which default
* support is provided in Gson. The tests for Map types are available in {@link MapTest}.
2008-09-01 05:13:32 +02:00
*
* @author Inderjeet Singh
* @author Joel Leitch
*/
public class DefaultTypeAdaptersTest extends TestCase {
private Gson gson;
private TimeZone oldTimeZone;
2008-09-01 05:13:32 +02:00
@Override
protected void setUp() throws Exception {
super.setUp();
this.oldTimeZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
Locale.setDefault(Locale.US);
2008-09-01 05:13:32 +02:00
gson = new Gson();
}
@Override
protected void tearDown() throws Exception {
TimeZone.setDefault(oldTimeZone);
super.tearDown();
}
2008-09-01 05:13:32 +02:00
public void testUrlSerialization() throws Exception {
String urlValue = "http://google.com/";
URL url = new URL(urlValue);
assertEquals("\"http://google.com/\"", gson.toJson(url));
2008-09-01 05:13:32 +02:00
}
public void testUrlDeserialization() {
String urlValue = "http://google.com/";
String json = "'http:\\/\\/google.com\\/'";
2008-09-01 05:13:32 +02:00
URL target = gson.fromJson(json, URL.class);
assertEquals(urlValue, target.toExternalForm());
gson.fromJson('"' + urlValue + '"', URL.class);
assertEquals(urlValue, target.toExternalForm());
2008-09-01 05:13:32 +02:00
}
public void testUrlNullSerialization() throws Exception {
ClassWithUrlField target = new ClassWithUrlField();
assertEquals("{}", gson.toJson(target));
}
public void testUrlNullDeserialization() {
String json = "{}";
ClassWithUrlField target = gson.fromJson(json, ClassWithUrlField.class);
assertNull(target.url);
}
private static class ClassWithUrlField {
URL url;
}
2008-09-01 05:13:32 +02:00
public void testUriSerialization() throws Exception {
String uriValue = "http://google.com/";
URI uri = new URI(uriValue);
assertEquals("\"http://google.com/\"", gson.toJson(uri));
2008-09-01 05:13:32 +02:00
}
public void testUriDeserialization() {
String uriValue = "http://google.com/";
String json = '"' + uriValue + '"';
URI target = gson.fromJson(json, URI.class);
assertEquals(uriValue, target.toASCIIString());
}
public void testUuidSerialization() throws Exception {
String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
UUID uuid = UUID.fromString(uuidValue);
assertEquals('"' + uuidValue + '"', gson.toJson(uuid));
}
public void testUuidDeserialization() {
String uuidValue = "c237bec1-19ef-4858-a98e-521cf0aad4c0";
String json = '"' + uuidValue + '"';
UUID target = gson.fromJson(json, UUID.class);
assertEquals(uuidValue, target.toString());
}
2008-09-01 05:13:32 +02:00
public void testLocaleSerializationWithLanguage() {
Locale target = new Locale("en");
assertEquals("\"en\"", gson.toJson(target));
}
public void testLocaleDeserializationWithLanguage() {
String json = "\"en\"";
Locale locale = gson.fromJson(json, Locale.class);
assertEquals("en", locale.getLanguage());
}
public void testLocaleSerializationWithLanguageCountry() {
Locale target = Locale.CANADA_FRENCH;
assertEquals("\"fr_CA\"", gson.toJson(target));
}
public void testLocaleDeserializationWithLanguageCountry() {
String json = "\"fr_CA\"";
Locale locale = gson.fromJson(json, Locale.class);
assertEquals(Locale.CANADA_FRENCH, locale);
}
public void testLocaleSerializationWithLanguageCountryVariant() {
Locale target = new Locale("de", "DE", "EURO");
String json = gson.toJson(target);
assertEquals("\"de_DE_EURO\"", json);
}
public void testLocaleDeserializationWithLanguageCountryVariant() {
String json = "\"de_DE_EURO\"";
Locale locale = gson.fromJson(json, Locale.class);
assertEquals("de", locale.getLanguage());
assertEquals("DE", locale.getCountry());
assertEquals("EURO", locale.getVariant());
}
public void testBigDecimalFieldSerialization() {
ClassWithBigDecimal target = new ClassWithBigDecimal("-122.01e-21");
String json = gson.toJson(target);
String actual = json.substring(json.indexOf(':') + 1, json.indexOf('}'));
assertEquals(target.value, new BigDecimal(actual));
}
public void testBigDecimalFieldDeserialization() {
ClassWithBigDecimal expected = new ClassWithBigDecimal("-122.01e-21");
String json = expected.getExpectedJson();
ClassWithBigDecimal actual = gson.fromJson(json, ClassWithBigDecimal.class);
assertEquals(expected.value, actual.value);
}
public void testBadValueForBigDecimalDeserialization() {
try {
gson.fromJson("{\"value\"=1.5e-1.0031}", ClassWithBigDecimal.class);
fail("Exponent of a BigDecimal must be an integer value.");
} catch (JsonParseException expected) { }
}
public void testBigIntegerFieldSerialization() {
ClassWithBigInteger target = new ClassWithBigInteger("23232323215323234234324324324324324324");
String json = gson.toJson(target);
assertEquals(target.getExpectedJson(), json);
}
public void testBigIntegerFieldDeserialization() {
ClassWithBigInteger expected = new ClassWithBigInteger("879697697697697697697697697697697697");
String json = expected.getExpectedJson();
ClassWithBigInteger actual = gson.fromJson(json, ClassWithBigInteger.class);
assertEquals(expected.value, actual.value);
}
public void testSetSerialization() throws Exception {
Gson gson = new Gson();
HashSet<String> s = new HashSet<String>();
s.add("blah");
String json = gson.toJson(s);
assertEquals("[\"blah\"]", json);
json = gson.toJson(s, Set.class);
assertEquals("[\"blah\"]", json);
}
public void testBitSetSerialization() throws Exception {
Gson gson = new Gson();
BitSet bits = new BitSet();
bits.set(1);
bits.set(3, 6);
bits.set(9);
String json = gson.toJson(bits);
assertEquals("[0,1,0,1,1,1,0,0,0,1]", json);
}
public void testBitSetDeserialization() throws Exception {
BitSet expected = new BitSet();
expected.set(0);
expected.set(2, 6);
expected.set(8);
Gson gson = new Gson();
String json = gson.toJson(expected);
assertEquals(expected, gson.fromJson(json, BitSet.class));
json = "[1,0,1,1,1,1,0,0,1,0,0,0]";
assertEquals(expected, gson.fromJson(json, BitSet.class));
json = "[\"1\",\"0\",\"1\",\"1\",\"1\",\"1\",\"0\",\"0\",\"1\"]";
assertEquals(expected, gson.fromJson(json, BitSet.class));
json = "[true,false,true,true,true,true,false,false,true,false,false]";
assertEquals(expected, gson.fromJson(json, BitSet.class));
}
2008-09-01 05:13:32 +02:00
public void testDefaultDateSerialization() {
Date now = new Date(1315806903103L);
2008-09-01 05:13:32 +02:00
String json = gson.toJson(now);
assertEquals("\"Sep 11, 2011 10:55:03 PM\"", json);
2008-09-01 05:13:32 +02:00
}
public void testDefaultDateDeserialization() {
String json = "'Dec 13, 2009 07:18:02 AM'";
Date extracted = gson.fromJson(json, Date.class);
assertEqualsDate(extracted, 2009, 11, 13);
assertEqualsTime(extracted, 7, 18, 2);
}
// Date can not directly be compared with another instance since the deserialization loses the
// millisecond portion.
@SuppressWarnings("deprecation")
private void assertEqualsDate(Date date, int year, int month, int day) {
assertEquals(year-1900, date.getYear());
assertEquals(month, date.getMonth());
assertEquals(day, date.getDate());
}
@SuppressWarnings("deprecation")
private void assertEqualsTime(Date date, int hours, int minutes, int seconds) {
assertEquals(hours, date.getHours());
assertEquals(minutes, date.getMinutes());
assertEquals(seconds, date.getSeconds());
}
public void testDefaultJavaSqlDateSerialization() {
java.sql.Date instant = new java.sql.Date(1259875082000L);
String json = gson.toJson(instant);
assertEquals("\"Dec 3, 2009\"", json);
}
public void testDefaultJavaSqlDateDeserialization() {
String json = "'Dec 3, 2009'";
java.sql.Date extracted = gson.fromJson(json, java.sql.Date.class);
assertEqualsDate(extracted, 2009, 11, 3);
}
public void testDefaultJavaSqlTimestampSerialization() {
Timestamp now = new java.sql.Timestamp(1259875082000L);
String json = gson.toJson(now);
assertEquals("\"Dec 3, 2009 1:18:02 PM\"", json);
}
public void testDefaultJavaSqlTimestampDeserialization() {
String json = "'Dec 3, 2009 1:18:02 PM'";
Timestamp extracted = gson.fromJson(json, Timestamp.class);
assertEqualsDate(extracted, 2009, 11, 3);
assertEqualsTime(extracted, 13, 18, 2);
}
public void testDefaultJavaSqlTimeSerialization() {
Time now = new Time(1259875082000L);
String json = gson.toJson(now);
assertEquals("\"01:18:02 PM\"", json);
}
public void testDefaultJavaSqlTimeDeserialization() {
String json = "'1:18:02 PM'";
Time extracted = gson.fromJson(json, Time.class);
assertEqualsTime(extracted, 13, 18, 2);
}
2008-09-01 05:13:32 +02:00
public void testDefaultDateSerializationUsingBuilder() throws Exception {
Gson gson = new GsonBuilder().create();
Date now = new Date(1315806903103L);
2008-09-01 05:13:32 +02:00
String json = gson.toJson(now);
assertEquals("\"Sep 11, 2011 10:55:03 PM\"", json);
2008-09-01 05:13:32 +02:00
}
public void testDefaultDateDeserializationUsingBuilder() throws Exception {
Gson gson = new GsonBuilder().create();
Date now = new Date(1315806903103L);
String json = gson.toJson(now);
Date extracted = gson.fromJson(json, Date.class);
assertEquals(now.toString(), extracted.toString());
}
public void testDefaultCalendarSerialization() throws Exception {
Gson gson = new GsonBuilder().create();
String json = gson.toJson(Calendar.getInstance());
assertTrue(json.contains("year"));
assertTrue(json.contains("month"));
assertTrue(json.contains("dayOfMonth"));
assertTrue(json.contains("hourOfDay"));
assertTrue(json.contains("minute"));
assertTrue(json.contains("second"));
}
public void testDefaultCalendarDeserialization() throws Exception {
Gson gson = new GsonBuilder().create();
String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}";
Calendar cal = gson.fromJson(json, Calendar.class);
assertEquals(2009, cal.get(Calendar.YEAR));
assertEquals(2, cal.get(Calendar.MONTH));
assertEquals(11, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(14, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(29, cal.get(Calendar.MINUTE));
assertEquals(23, cal.get(Calendar.SECOND));
}
public void testDefaultGregorianCalendarSerialization() throws Exception {
Gson gson = new GsonBuilder().create();
GregorianCalendar cal = new GregorianCalendar();
String json = gson.toJson(cal);
assertTrue(json.contains("year"));
assertTrue(json.contains("month"));
assertTrue(json.contains("dayOfMonth"));
assertTrue(json.contains("hourOfDay"));
assertTrue(json.contains("minute"));
assertTrue(json.contains("second"));
}
public void testDefaultGregorianCalendarDeserialization() throws Exception {
Gson gson = new GsonBuilder().create();
String json = "{year:2009,month:2,dayOfMonth:11,hourOfDay:14,minute:29,second:23}";
GregorianCalendar cal = gson.fromJson(json, GregorianCalendar.class);
assertEquals(2009, cal.get(Calendar.YEAR));
assertEquals(2, cal.get(Calendar.MONTH));
assertEquals(11, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(14, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(29, cal.get(Calendar.MINUTE));
assertEquals(23, cal.get(Calendar.SECOND));
}
2008-09-01 05:13:32 +02:00
public void testDateSerializationWithPattern() throws Exception {
String pattern = "yyyy-MM-dd";
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
Date now = new Date(1315806903103L);
2008-09-01 05:13:32 +02:00
String json = gson.toJson(now);
assertEquals("\"2011-09-11\"", json);
2008-09-01 05:13:32 +02:00
}
@SuppressWarnings("deprecation")
public void testDateDeserializationWithPattern() throws Exception {
String pattern = "yyyy-MM-dd";
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).setDateFormat(pattern).create();
Date now = new Date(1315806903103L);
String json = gson.toJson(now);
Date extracted = gson.fromJson(json, Date.class);
assertEquals(now.getYear(), extracted.getYear());
assertEquals(now.getMonth(), extracted.getMonth());
assertEquals(now.getDay(), extracted.getDay());
}
public void testDateSerializationWithPatternNotOverridenByTypeAdapter() throws Exception {
String pattern = "yyyy-MM-dd";
Gson gson = new GsonBuilder()
.setDateFormat(pattern)
.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new Date(1315806903103L);
}
})
.create();
Date now = new Date(1315806903103L);
String json = gson.toJson(now);
assertEquals("\"2011-09-11\"", json);
}
// http://code.google.com/p/google-gson/issues/detail?id=230
public void testDateSerializationInCollection() throws Exception {
Type listOfDates = new TypeToken<List<Date>>() {}.getType();
TimeZone defaultTimeZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Locale defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.US);
try {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
List<Date> dates = Arrays.asList(new Date(0));
String json = gson.toJson(dates, listOfDates);
assertEquals("[\"1970-01-01\"]", json);
assertEquals(0L, gson.<List<Date>>fromJson("[\"1970-01-01\"]", listOfDates).get(0).getTime());
} finally {
TimeZone.setDefault(defaultTimeZone);
Locale.setDefault(defaultLocale);
}
}
// http://code.google.com/p/google-gson/issues/detail?id=230
public void testTimestampSerialization() throws Exception {
TimeZone defaultTimeZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Locale defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.US);
try {
Timestamp timestamp = new Timestamp(0L);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
String json = gson.toJson(timestamp, Timestamp.class);
assertEquals("\"1970-01-01\"", json);
assertEquals(0, gson.fromJson("\"1970-01-01\"", Timestamp.class).getTime());
} finally {
TimeZone.setDefault(defaultTimeZone);
Locale.setDefault(defaultLocale);
}
}
// http://code.google.com/p/google-gson/issues/detail?id=230
public void testSqlDateSerialization() throws Exception {
TimeZone defaultTimeZone = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Locale defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.US);
try {
java.sql.Date sqlDate = new java.sql.Date(0L);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
String json = gson.toJson(sqlDate, Timestamp.class);
assertEquals("\"1970-01-01\"", json);
assertEquals(0, gson.fromJson("\"1970-01-01\"", java.sql.Date.class).getTime());
} finally {
TimeZone.setDefault(defaultTimeZone);
Locale.setDefault(defaultLocale);
}
}
2008-09-01 05:13:32 +02:00
private static class ClassWithBigDecimal {
BigDecimal value;
ClassWithBigDecimal(String value) {
this.value = new BigDecimal(value);
}
String getExpectedJson() {
return "{\"value\":" + value.toEngineeringString() + "}";
}
}
private static class ClassWithBigInteger {
BigInteger value;
ClassWithBigInteger(String value) {
this.value = new BigInteger(value);
}
String getExpectedJson() {
return "{\"value\":" + value + "}";
}
}
2008-12-31 01:43:40 +01:00
public void testPropertiesSerialization() {
Properties props = new Properties();
props.setProperty("foo", "bar");
2008-12-31 01:43:40 +01:00
String json = gson.toJson(props);
String expected = "{\"foo\":\"bar\"}";
assertEquals(expected, json);
2008-12-31 01:43:40 +01:00
}
2008-12-31 01:43:40 +01:00
public void testPropertiesDeserialization() {
String json = "{foo:'bar'}";
Properties props = gson.fromJson(json, Properties.class);
assertEquals("bar", props.getProperty("foo"));
2008-12-31 01:43:40 +01:00
}
public void testTreeSetSerialization() {
TreeSet<String> treeSet = new TreeSet<String>();
treeSet.add("Value1");
String json = gson.toJson(treeSet);
assertEquals("[\"Value1\"]", json);
}
public void testTreeSetDeserialization() {
String json = "['Value1']";
Type type = new TypeToken<TreeSet<String>>() {}.getType();
TreeSet<String> treeSet = gson.fromJson(json, type);
assertTrue(treeSet.contains("Value1"));
}
public void testStringBuilderSerialization() {
StringBuilder sb = new StringBuilder("abc");
String json = gson.toJson(sb);
assertEquals("\"abc\"", json);
}
public void testStringBuilderDeserialization() {
StringBuilder sb = gson.fromJson("'abc'", StringBuilder.class);
assertEquals("abc", sb.toString());
}
public void testStringBufferSerialization() {
StringBuffer sb = new StringBuffer("abc");
String json = gson.toJson(sb);
assertEquals("\"abc\"", json);
}
public void testStringBufferDeserialization() {
StringBuffer sb = gson.fromJson("'abc'", StringBuffer.class);
assertEquals("abc", sb.toString());
}
2008-09-01 05:13:32 +02:00
}