A Java serialization/deserialization library to convert Java Objects into JSON and back

Related tags

JSON gson
Overview

Gson

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.

Goals

  • Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
  • Allow pre-existing unmodifiable objects to be converted to and from JSON
  • Extensive support of Java Generics
  • Allow custom representations for objects
  • Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)

Download

Gradle:

dependencies {
  implementation 'com.google.code.gson:gson:2.8.6'
}

Maven:

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.6</version>
</dependency>

Gson jar downloads are available from Maven Central.

Build Status

Documentation

  • API Javadoc: Documentation for the current release
  • User guide: This guide contains examples on how to use Gson in your code.
  • Change log: Changes in the recent versions
  • Design document: This document discusses issues we faced while designing Gson. It also includes a comparison of Gson with other Java libraries that can be used for Json conversion

Please use the 'gson' tag on StackOverflow or the google-gson Google group to discuss Gson or to post questions.

Related Content Created by Third Parties

License

Gson is released under the Apache 2.0 license.

Copyright 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.

Disclaimer

This is not an officially supported Google product.

Comments
  • Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $

    Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $

    com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $ at com.google.gson.Gson.fromJson(Gson.java:826) at com.google.gson.Gson.fromJson(Gson.java:779) at com.google.gson.Gson.fromJson(Gson.java:728) at readtv.ghs.tv.util.RewardRuleUtil$1.onSuccess(RewardRuleUtil.java:63) at readtv.ghs.tv.http.AsyncHttpClient$2$2.run(AsyncHttpClient.java:116) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5013) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:811) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:627) Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $ at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60) at com.google.gson.Gson.fromJson(Gson.java:814) ... 12 more java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $ at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79) at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60) at com.google.gson.Gson.fromJson(Gson.java:814) at com.google.gson.Gson.fromJson(Gson.java:779) at com.google.gson.Gson.fromJson(Gson.java:728) at readtv.ghs.tv.util.RewardRuleUtil$1.onSuccess(RewardRuleUtil.java:63) at readtv.ghs.tv.http.AsyncHttpClient$2$2.run(AsyncHttpClient.java:116) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5013) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:811) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:627)

    Often this kind of problem, I hope you can tell me how to deal with the simple. Or where it is. I don't think it's our problem.

    opened by LucianWang 49
  • java.lang.IncompatibleClassChangeError

    java.lang.IncompatibleClassChangeError

    I'm getting this crash lately. It complains about SerializedName class missing the "value" method.

    This is the stacktrace:

    java.lang.IncompatibleClassChangeError: Couldn't find com.google.gson.annotations.SerializedName.value
    at libcore.reflect.AnnotationAccess.toAnnotationInstance(AnnotationAccess.java:659)
    at libcore.reflect.AnnotationAccess.toAnnotationInstance(AnnotationAccess.java:641)
    at libcore.reflect.AnnotationAccess.getDeclaredAnnotation(AnnotationAccess.java:170)
    at java.lang.reflect.Field.getAnnotation(Field.java:242)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldName(ReflectiveTypeAdapterFactory.java:71)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldName(ReflectiveTypeAdapterFactory.java:67)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
    at com.google.gson.Gson.getAdapter(Gson.java:359)
    at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:52)
    at com.google.gson.Gson.getAdapter(Gson.java:359)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.(ReflectiveTypeAdapterFactory.java:92)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
    at com.google.gson.Gson.getAdapter(Gson.java:359)
    at com.google.gson.Gson.fromJson(Gson.java:809)
    at com.google.gson.Gson.fromJson(Gson.java:875)
    at com.google.gson.Gson.fromJson(Gson.java:848)
    
    opened by kdehairy 43
  • Android M: Cannot make field constructor accessible

    Android M: Cannot make field constructor accessible

    D/Retrofit﹕java.lang.SecurityException: Can't make field constructor accessible
                at java.lang.reflect.Constructor.setAccessible(Constructor.java:334)
                at com.google.gson.internal.ConstructorConstructor.newDefaultConstructor(ConstructorConstructor.java:97)
                at com.google.gson.internal.ConstructorConstructor.get(ConstructorConstructor.java:79)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:82)
                at com.google.gson.Gson.getAdapter(Gson.java:359)
                at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:52)
                at com.google.gson.Gson.getAdapter(Gson.java:359)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:92)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
                at com.google.gson.Gson.getAdapter(Gson.java:359)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:92)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
                at com.google.gson.Gson.getAdapter(Gson.java:359)
                at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:52)
                at com.google.gson.Gson.getAdapter(Gson.java:359)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getFieldAdapter(ReflectiveTypeAdapterFactory.java:122)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.access$100(ReflectiveTypeAdapterFactory.java:46)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:92)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:91)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:142)
                at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:83)
                at com.google.gson.Gson.getAdapter(Gson.java:359)
                at com.google.gson.Gson.fromJson(Gson.java:809)
                at com.google.gson.Gson.fromJson(Gson.java:775)
                at retrofit.converter.GsonConverter.fromBody(GsonConverter.java:63)
                at retrofit.RestAdapter$RestHandler.invokeRequest(RestAdapter.java:367)
                at retrofit.RestAdapter$RestHandler.access$100(RestAdapter.java:220)
                at retrofit.RestAdapter$RestHandler$2.obtainResponse(RestAdapter.java:278)
                at retrofit.CallbackRunnable.run(CallbackRunnable.java:42)
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                at retrofit.Platform$Android$2$1.run(Platform.java:142)
                at java.lang.Thread.run(Thread.java:818)
    

    Originally filed at https://github.com/square/retrofit/issues/870.

    Note: this might be a bug in the preview OS runtime and not Gson, but it's definitely not a Retrofit problem.

    Priority-High 
    opened by JakeWharton 39
  • Gson doesn't deserialise Long numbers correctly

    Gson doesn't deserialise Long numbers correctly

    Gson shouldn't cast a number to a Double if a number does not have decimal digits. It's clearly wrong.

    public class GsonVsJackson {
    
    
        public static void main(String[] args) throws Exception {
            testGson();
            System.out.println("========================");
            testJackson();
        }
    
        public static void testGson() {
            System.out.println("Testing Gson 2.8");
            Gson gson = new Gson();
            HashMap<String, Object> newTest = new HashMap<>();
            newTest.put("first", 6906764140092371368L);
            String jsonString = gson.toJson(newTest);
            System.out.println(jsonString); // output ok: {"first":6906764140092371368}
            Map<String, Object> mapFromJson = gson.fromJson(jsonString, Map.class);
            Number numberFromJson = (Number) mapFromJson.get("first");
            System.out.println(numberFromJson.getClass() + " = " + numberFromJson); // java.lang.Double val 6.9067641400923709E18
            long longVal = numberFromJson.longValue();
            System.out.println(longVal); // output rounded: 6906764140092370944
        }
    
        public static void testJackson() throws Exception {
            System.out.println("Testing Jackson");
            ObjectMapper jackson = new ObjectMapper();
            HashMap<String, Object> newTest = new HashMap<>();
            newTest.put("first", 6906764140092371368L);
            String jsonString = jackson.writeValueAsString(newTest);
            System.out.println(jsonString); // output ok: {"first":6906764140092371368}
            Map<String, Object> mapFromJson = jackson.readValue(jsonString, Map.class);
            Number numberFromJson = (Number) mapFromJson.get("first");
            System.out.println(numberFromJson.getClass() + " = " + numberFromJson); // java.math.BigInteger = 6906764140092371368
            long longVal = numberFromJson.longValue();
            System.out.println(longVal); // output OK: 6906764140092371368
        }
    
    }
    

    Kind Regards, Daniele

    opened by xavix-yo 37
  • Memory Leak in web application

    Memory Leak in web application

    What steps will reproduce the problem?
    1. Use on web application / Tomcat , view log
    2.
    3.
    
    What is the expected output? What do you see instead?
    Expected None / Warning
    
    What version of the product are you using? On what operating system?
    CentOS/ Apache Tomcat Version 7.0.12
    
    Please provide any additional information below.
    
    Jan 26, 2012 12:09:41 AM org.apache.catalina.loader.WebappClassLoader 
    checkThreadLocalMapForLeaks
    SEVERE: The web application [] created a ThreadLocal with key of type 
    [com.google.gson.internal.bind.MiniGson$1] (value 
    [com.google.gson.internal.bind.MiniGson$1@73055179]) and a value of type 
    [java.util.HashMap] (value [{}]) but failed to remove it when the web 
    application was stopped. Threads are going to be renewed over time to try and 
    avoid a probable memory leak.
    

    Original issue reported on code.google.com by [email protected] on 26 Jan 2012 at 6:17

    opened by GoogleCodeExporter 34
  • Deserialization with Gson.fromJson() should *ignore* missing fields

    Deserialization with Gson.fromJson() should *ignore* missing fields

    What steps will reproduce the problem?
    
    1. Create a simple *non-static* class which initializes default values for some 
    fields:
    
        public class Test {
    
            int x = -1;
            String s = "Hello";
        }
    
    2. Create new Gson and call `fromJson()` with missing fields:
    
        Test t = new Gson().fromJson("{}", Test.class);
        System.out.println(String.format("x=[%s] s=[%s]", t.x, t.s));
    
    >> Results: x=[0] s=[null]
    
        Test t = new Gson().fromJson("{\"x\": 1}", Test.class);
        System.out.println(String.format("x=[%s] s=[%s]", t.x, t.s));
    
    >> Results: x=[1] s=[null]
    
    What is the expected output? What do you see instead?
    
    As the test cases, I would like to expect default value for each field to be 
    the one that the class initializes. For instance with the first test case, `x` 
    should be `-1` and `s` should be "Hello".
    
    What version of the product are you using? On what operating system?
    
     - Gson 2.2.3
     - OSes:
       + Fedora 18, 64 bit with OpenJDK 1.7.0_19;
       + Android API 4 and API 17;
    
    Thanks,
    Hai
    

    Original issue reported on code.google.com by [email protected] on 5 May 2013 at 8:23

    opened by GoogleCodeExporter 33
  • Support arbitrary Number implementation for Object and Number deserialization

    Support arbitrary Number implementation for Object and Number deserialization

    RFC 8259, 6 Numbers allows numbers of arbitrary range and precision specifying that a particular implementation may set some limits for numeric values. As of Gson 2.8.4 uses the following deserialization strategies:

    • If the result type is declared as Object, Gson always returns Doubles for all encountered JSON numbers. In this case, the minimum and maximum hold number value fits the limits of Double which cannot hold exact Long values that exceed the Double exact precision limits (2^53+1).
    • ‎If the result type is declared as Number and there are no custom Number adapters, Gson always returns LazilyParsedNumbers that hold original string values parsing them to a requested type lazily allowing to use the whole range of Long. However, it does not allow to use numbers of arbitrary range and precision, and does not expose its hold string as a BigDecimal.

    In order to fix these limitations and preserve backwards compatibility, some sort of "to-number" strategies might be accepted in GsonBuilder to override the default behavior of Gson. This pull-request introduces such a strategy interface to be used in the built-in Object and Number type adapters. There are also four strategies implemented in this PR (two standard to keep the backwards compatibility and two enhanced to overcome the limitations) using an enumeration:

    • ToNumberPolicy.DOUBLE that implements the default behavior of the Object type adapter returning Doubles only.
    • ToNumberPolicy.LAZILY_PARSED_NUMBER that implements the default behavior of the Number type adapter.
    • ToNumberPolicy.LONG_OR_DOUBLE that tries to parse a number as a Long, otherwise then tries to parse it as a Double, if the number cannot be parsed as a Long.
    • ToNumberPolicy.BIG_DECIMAL that can parse numbers of arbitrary range and precision.

    Call-site is expected to extract proper values using the methods declared in java.lang.Number.

    Examples of use:

    Default behavior, backwards-compatible with the previous versions of Gson

    Gson gson = new GsonBuilder()
      .setObjectToNumberStrategy(ToNumberPolicy.DOUBLE) // explicit default, may be omitted
      .create();
    List<Object> actual = gson.fromJson("[null, 10, 10.0]", new TypeToken<List<Object>>() {}.getType());
    List<Double> expected = Arrays.asList(null, 10.0, 10.0);
    assertEquals(expected, actual);
    
    Gson gson = new GsonBuilder()
        .setNumberToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER) // explicit default, may be omitted
        .create();
    List<Number> actual = gson.fromJson("[null, 10, 10.0]", new TypeToken<List<Number>>() {}.getType());
    List<Object> expected = Arrays.<Object>asList(null, new LazilyParsedNumber("10"), new LazilyParsedNumber("10.0"));
    assertEquals(expected, actual);
    

    Object-declared numbers are always LazilyParsedNumbers

    Gson gson = new GsonBuilder()
      .setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
      .create();
    List<Object> actual = gson.fromJson("[null, 10, 10.0]", new TypeToken<List<Object>>() {}.getType());
    List<LazilyParsedNumber> expected = Arrays.asList(null, new LazilyParsedNumber("10"), new LazilyParsedNumber("10.0"));
    assertEquals(expected, actual);
    

    Number-declared numbers are always Doubles

    Gson gson = new GsonBuilder()
      .setNumberToNumberStrategy(ToNumberPolicy.DOUBLE)
      .create();
    List<Number> actual = gson.fromJson("[null, 10, 10.0]", new TypeToken<List<Number>>() {}.getType());
    List<Double> expected = Arrays.asList(null, 10.0, 10.0);
    assertEquals(expected, actual);
    

    Object-declared numbers are either Long or Double

    Gson gson = new GsonBuilder()
      .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
      .create();
    List<Object> actual = gson.fromJson("[null, 10, 10.0]", new TypeToken<List<Object>>() {}.getType());
    List<? extends Number> expected = Arrays.asList(null, 10L, 10.0);
    assertEquals(expected, actual);
    

    Object-declared numbers are BigDecimals

    Gson gson = new GsonBuilder()
      .setObjectToNumberStrategy(ToNumberPolicy.BIG_DECIMAL)
      .create();
    List<Object> actual = gson.fromJson("[null, 3.141592653589793238462643383279, 1e400]", new TypeToken<List<Object>>() {}.getType());
    List<BigDecimal> expected = Arrays.asList(null, new BigDecimal("3.141592653589793238462643383279"), new BigDecimal("1e400"));
    assertEquals(expected, actual);
    

    Custom bytes-only:

    Gson gson = new GsonBuilder()
      .setObjectToNumberStrategy(new ToNumberStrategy() {
        @Override
        public Byte toNumber(final JsonReader in)
                throws IOException {
          return (byte) in.nextInt();
        }
      })
      .create();
    List<Object> actual = gson.fromJson("[null, 10, 20, 30]", new TypeToken<List<Object>>() {}.getType());
    List<Byte> expected = Arrays.asList(null, (byte) 10, (byte) 20, (byte) 30);
    assertEquals(expected, actual);
    

    Custom deserialization does not affect Byte-declared deserialization:

    ToNumberStrategy fail = new ToNumberStrategy() {
        @Override
        public Byte toNumber(final JsonReader in) {
          throw new AssertionError();
        }
      };
    Gson gson = new GsonBuilder()
      .setObjectToNumberStrategy(fail)
      .setNumberToNumberStrategy(fail)
      .create();
    List<Object> actual = gson.fromJson("[null, 10, 20, 30]", new TypeToken<List<Byte>>() {}.getType());
    List<Byte> expected = Arrays.asList(null, (byte) 10, (byte) 20, (byte) 30);
    assertEquals(expected, actual);
    
    cla: yes 
    opened by lyubomyr-shaydariv 27
  • Why deepCopy is not public?

    Why deepCopy is not public?

    Is there a reason why the deepCopy methods are not public? I see that they were public for some time in an earlier revision then was made "default" access level but I couldn't find the reason.

    opened by kramer 27
  • Java 14/15 records can not set final field

    Java 14/15 records can not set final field

    Hi, as the following error describes, java records (preview feature) deserialization isn't working in gson, Jackson is adding support in its very soon release 2.12, is there going to be same support/fix in gson ?

    java.lang.AssertionError: AssertionError (GSON 2.8.6): java.lang.IllegalAccessException: Can not set final java.lang.String field JsonGsonRecordTest$Emp.name to java.lang.String

    Here's a sample test

      record Emp(String name) {}
    
      @Test
      void deserializeEngineer() {
        Gson j = new GsonBuilder().setPrettyPrinting().create();
        var empJson = """
                {
                  "name": "bob"
                }""";
        var empObj = j.fromJson(empJson, Emp.class);
      }
    
    enhancement 
    opened by IsmailMarmoush 25
  • Dynamic serialization and deserialization via class interface

    Dynamic serialization and deserialization via class interface

    I have created a patch against gson-2.1 that adds code for allowing classes to 
    define serialization and deserialization by implementing a simple interface. 
    The benefit of this approach is that there is no longer a need to register 
    special handlers for each class that requires custom serialization. It can be 
    used as follows:
    
    public class Foo implements JsonSerialization, 
    JsonDeserializedBy<FooDeserializer> {
        public String name;
        public JsonElement serialize (JsonSerializationContext jsc) {
            return new JsonPrimitive(name);
        }
    }
    
    public class FooDeserializer implements JsonDeserializer<Foo> {
        public Foo deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) {
            Foo f = new Foo();
            f.name = je.getAsString();
            return f;
        }
    }
    
    ...
    Foo foo = new Foo();
    foo.name = "foo";
    gson.toJson(foo); // "foo"
    gson.fromJson(gson.toJson(foo), Foo.class).name; // "foo"
    
    With my patch, a Gson object now checks the argument sent to toJson to 
    determine if it implements JsonSerialization. If so, it calls its 
    serialize(jsc) method to retrieve a JsonElement for that class.
    
    When fromJson is called, the given class is inspected to determine if it 
    implements the JsonDeserializer interface. If so, the class specified in the 
    template parameter (in this case FooDeserializer) is used for deserialization 
    by creating a new instance of that class (using the no-argument constructor), 
    and then deserialize is called as with any JsonDeserializer object.
    
    This patch adds the two new interfaces (JsonSerialization and 
    JsonDeserialization) and adds a few lines of code to Gson in order to provide 
    the aforementioned functionality. I'm not sure I chose the appropriate location 
    to insert the functionality, and the code is pretty ugly, but it seems to work 
    pretty well in my limited test cases.
    
    I'll license the patch under the same license as gson, in case anyone is 
    concerned about that.
    

    Original issue reported on code.google.com by [email protected] on 12 Jan 2012 at 1:59

    Attachments:

    opened by GoogleCodeExporter 24
  • Double cannot be casted to Integer.

    Double cannot be casted to Integer.

    Long cannot be casted to Integer, Integer cannot be casted to Short, etc. Could you fix it in https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/internal/bind/ObjectTypeAdapter.java? When serializing Map<String, Object> and deserializing, it throws Exception. I can't edit this, because I can't edit Spigot/Bukkit. If JSON save Integer, it should read Integer, not make Double unnecessarily.

    I maked it in issue, because I had to download sources GSON and edit this:.

        case NUMBER:
          try {
            return in.nextInt();
          } catch(NumberFormatException exception) {
          }
          try {
            return in.nextLong();
          } catch(NumberFormatException exception) {
          }
          return in.nextDouble();
    
    opened by adiantek 23
  • Strict mode for JSON parsing

    Strict mode for JSON parsing

    As noted in the documentation for JsonReader.setLenient, there are a number of areas where Gson accepts JSON inputs that are not strictly conformant, even when lenient mode is off:

    • JsonReader allows the literals true, false and null to have any capitalization, for example fAlSe
    • JsonReader supports the escape sequence \', representing a '
    • JsonReader supports the escape sequence \LF (with LF being the Unicode character U+000A), resulting in a LF within the read JSON string
    • JsonReader allows unescaped control characters (U+0000 through U+001F)

    To which we could add that it allows a trailing comma in JSON objects, for example {"foo": "bar", "baz": "buh",} as noted in #494.

    We could imagine that GsonBuilder would acquire a method setStrict(), mutually exclusive with setLenient() and that JsonReader would likewise acquire setStrict(boolean) and isStrict(). We can't make strict mode the default, for fear of breaking existing users, but we could recommend it.

    enhancement 
    opened by eamonnmcmanus 0
  • Clean up Gson source code

    Clean up Gson source code

    We've been reluctant to make large-scale changes because they are likely to cause pain for people with unmerged PRs. But at this point I think there are relatively few open PRs that we are likely to merge, thanks largely to the heroic work of @Marcono1234. So this would be as good a time as any to consider at least:

    • Port tests from JUnit 3 to JUnit 4. (Google's internal systems don't support JUnit 5 so we can't use that.)
    • Use Truth for clearer assertions in tests.
    • Apply various automated fixes suggested by Error Prone and the like.
    • Reformat all source files with google-java-format. Possibly also install a check that ensures that future PRs are also correctly formatted.
    Priority-Medium Type-Task 
    opened by eamonnmcmanus 10
  • Fixes #776: Add settings for the kind of newline to use

    Fixes #776: Add settings for the kind of newline to use

    Addresses https://github.com/google/gson/issues/776

    I don't think that setFormattingStyles(String style) (as proposed) should affect the newline, that would be orthogonal.

    That idea has no explanation, but I'm thinking that it would be something similar to the formatting styles in programming languages (where to break and how to indent, for example K&R vs Linux kernel vs BSD KNF, etc.) If that is the idea then the kind of newline to use is not related to the style.

    The "dangling new line at the end of the JSON" would indeed be part of the style.

    opened by mihnita 15
  • Add `JsonDeserializationContext.deserialize` overload with `TypeToken` parameter

    Add `JsonDeserializationContext.deserialize` overload with `TypeToken` parameter

    Problem solved by the feature

    Similar to #1700 JsonDeserializationContext should have a deserialize overload with TypeToken parameter to provide type-safety, and the documentation should then recommend that overload.

    Feature description

    Since JsonDeserializationContext is an interface and might be implemented by users, the deserialize overload would have to be implemented as interface default method. Therefore this has to wait until Gson targets Java 8 or newer. The default method could then simply delegate to the other overload, though Gson's internal implementation could override it to directly call Gson.fromJson(..., TypeToken).

    enhancement 
    opened by Marcono1234 0
Releases(gson-parent-2.10)
  • gson-parent-2.10(Oct 25, 2022)

    Most important changes

    • Support for serializing and deserializing Java records, on Java ≥ 16. (#2201)

    • Add JsonArray.asList and JsonObject.asMap view methods (#2225)

    • Fix TypeAdapterRuntimeTypeWrapper not detecting reflective TreeTypeAdapter and FutureTypeAdapter (#1787)

    • Improve JsonReader.skipValue() (#2062)

    • Perform numeric conversion for primitive numeric type adapters (#2158)

    • Add Gson.fromJson(..., TypeToken) overloads (#1700)

    • Fix changes to GsonBuilder affecting existing Gson instances (#1815)

    • Make JsonElement conversion methods more consistent and fix javadoc (#2178)

    • Throw UnsupportedOperationException when JsonWriter.jsonValue is not supported (#1651)

    • Disallow JsonObject Entry.setValue(null) (#2167)

    • Fix TypeAdapter.toJson throwing AssertionError for custom IOException (#2172)

    • Convert null to JsonNull for JsonArray.set (#2170)

    • Fixed nullSafe usage. (#1555)

    • Validate TypeToken.getParameterized arguments (#2166)

    • Fix #1702: Gson.toJson creates CharSequence which does not implement toString (#1703)

    • Prefer existing adapter for concurrent Gson.getAdapter calls (#2153)

    • Improve ArrayTypeAdapter for Object[] (#1716)

    • Improve AppendableWriter performance (#1706)

    List of all changes

    • Improve AppendableWriter performance by @Marcono1234 in https://github.com/google/gson/pull/1706
    • Improve ArrayTypeAdapter for Object[] by @Marcono1234 in https://github.com/google/gson/pull/1716
    • Prefer existing adapter for concurrent Gson.getAdapter calls by @Marcono1234 in https://github.com/google/gson/pull/2153
    • Fix #1702: Gson.toJson creates CharSequence which does not implement toString by @Marcono1234 in https://github.com/google/gson/pull/1703
    • Deprecate JsonElement constructor by @Marcono1234 in https://github.com/google/gson/pull/1761
    • Validate TypeToken.getParameterized arguments by @Marcono1234 in https://github.com/google/gson/pull/2166
    • Fixed nullSafe usage. by @bufistov in https://github.com/google/gson/pull/1555
    • Convert null to JsonNull for JsonArray.set by @Marcono1234 in https://github.com/google/gson/pull/2170
    • Clarify that GsonBuilder.setExclusionStrategies does not replace existing ones by @Marcono1234 in https://github.com/google/gson/pull/2168
    • Fix typo by @JamesZBL in https://github.com/google/gson/pull/1246
    • Remove not needed .gitattributes file by @Marcono1234 in https://github.com/google/gson/pull/1862
    • Improve InternationalizationTest by @Marcono1234 in https://github.com/google/gson/pull/1705
    • Fix JsonWriter documentation regarding top-level value by @Marcono1234 in https://github.com/google/gson/pull/1766
    • Fix JsonTreeReader throwing wrong exception type for non-finite doubles by @Marcono1234 in https://github.com/google/gson/pull/1782
    • Clarify doc about non-finite numbers for non-lenient JsonReader by @Marcono1234 in https://github.com/google/gson/pull/1723
    • Fix TypeAdapter.toJson throwing AssertionError for custom IOException by @Marcono1234 in https://github.com/google/gson/pull/2172
    • Add test for JsonArray.isEmpty() by @LorenzNickel in https://github.com/google/gson/pull/2173
    • Disallow JsonObject Entry.setValue(null) by @Marcono1234 in https://github.com/google/gson/pull/2167
    • Improve GsonTest.testGetAdapter_Concurrency by @Marcono1234 in https://github.com/google/gson/pull/2177
    • Add null checks for GsonBuilder methods by @Marcono1234 in https://github.com/google/gson/pull/2179
    • Throw UnsupportedOperationException when JsonWriter.jsonValue is not supported by @Marcono1234 in https://github.com/google/gson/pull/1651
    • Make JsonElement conversion methods more consistent and fix javadoc by @Marcono1234 in https://github.com/google/gson/pull/2178
    • Bump maven-javadoc-plugin from 3.4.0 to 3.4.1 by @dependabot in https://github.com/google/gson/pull/2175
    • Add tests checking GsonBuilder not affecting existing Gson instances by @Marcono1234 in https://github.com/google/gson/pull/1815
    • Fix #1697: Mention that GsonBuilder.registerTypeAdapter makes (de-)serializers null-safe by @Marcono1234 in https://github.com/google/gson/pull/1704
    • Replace $Gson$Preconditions.checkNotNull with Objects.requireNonNull by @Marcono1234 in https://github.com/google/gson/pull/2180
    • Verify that JsonTreeReader and JsonTreeWriter override all methods by @Marcono1234 in https://github.com/google/gson/pull/2181
    • Fail Maven build on compiler warnings; remove some warning suppressions by @Marcono1234 in https://github.com/google/gson/pull/2183
    • Add GitHub workflow for checking API compatibility by @Marcono1234 in https://github.com/google/gson/pull/2182
    • Bump japicmp-maven-plugin from 0.15.7 to 0.16.0 by @dependabot in https://github.com/google/gson/pull/2187
    • Bump jackson-databind from 2.13.3 to 2.13.4 by @dependabot in https://github.com/google/gson/pull/2191
    • Remove usage of oss-parent Maven parent and update ReleaseProcess.md by @Marcono1234 in https://github.com/google/gson/pull/2159
    • Improve documentation by @Marcono1234 in https://github.com/google/gson/pull/2193
    • updated JsonDeserializer example by @deeptimarrivada1 in https://github.com/google/gson/pull/2192
    • Add Gson.fromJson(..., TypeToken) overloads by @Marcono1234 in https://github.com/google/gson/pull/1700
    • Bump maven-jar-plugin from 3.2.2 to 3.3.0 by @dependabot in https://github.com/google/gson/pull/2195
    • Build on JDK 17 as well as 11. by @eamonnmcmanus in https://github.com/google/gson/pull/2198
    • Fix incorrect HTML headings in Javadoc by @Marcono1234 in https://github.com/google/gson/pull/2200
    • Add a currently-failing test for Java records and @Ignore it. by @eamonnmcmanus in https://github.com/google/gson/pull/2203
    • Follow-up for record test build changes by @Marcono1234 in https://github.com/google/gson/pull/2207
    • Disable Maven transfer progress for GitHub workflows by @Marcono1234 in https://github.com/google/gson/pull/2206
    • Only create one UnsafeAllocator instance by @kb-1000 in https://github.com/google/gson/pull/2196
    • Mention in User Guide alternative for Gson versions without fromJson(..., TypeToken) by @Marcono1234 in https://github.com/google/gson/pull/2209
    • Fix typo in GsonBuilder Javadoc by @BillyGalbreath in https://github.com/google/gson/pull/2213
    • Add Javadoc @since tags for previously added elements by @Marcono1234 in https://github.com/google/gson/pull/2211
    • Improve versioning support documentation and validate version by @Marcono1234 in https://github.com/google/gson/pull/2214
    • Perform numeric conversion for primitive numeric type adapters by @Marcono1234 in https://github.com/google/gson/pull/2158
    • Clarify in documentation that Gson might cache strategy results by @Marcono1234 in https://github.com/google/gson/pull/2215
    • Improve JsonReader.skipValue() by @Marcono1234 in https://github.com/google/gson/pull/2062
    • Fix TypeAdapterRuntimeTypeWrapper not detecting reflective TreeTypeAdapter and FutureTypeAdapter by @Marcono1234 in https://github.com/google/gson/pull/1787
    • Support Java Records when present in JVM. by @staale in https://github.com/google/gson/pull/2201
    • Small adjustments to the new record code. by @eamonnmcmanus in https://github.com/google/gson/pull/2219
    • Bump jackson-databind from 2.13.4 to 2.13.4.1 by @dependabot in https://github.com/google/gson/pull/2222
    • Bump jackson-databind from 2.13.4.1 to 2.13.4.2 by @dependabot in https://github.com/google/gson/pull/2223
    • Add JsonArray.asList and JsonObject.asMap view methods by @Marcono1234 in https://github.com/google/gson/pull/2225
    • Adjust Record adapter and extend test coverage by @Marcono1234 in https://github.com/google/gson/pull/2224
    • Small tweaks to fix Error Prone warnings. by @eamonnmcmanus in https://github.com/google/gson/pull/2227
    • Automatically replace version references on release:prepare by @Marcono1234 in https://github.com/google/gson/pull/2212
    • Revise the version regex in GsonVersionDiagnosticsTest. by @eamonnmcmanus in https://github.com/google/gson/pull/2228

    New Contributors

    • @bufistov made their first contribution in https://github.com/google/gson/pull/1555
    • @JamesZBL made their first contribution in https://github.com/google/gson/pull/1246
    • @xtay2 made their first contribution in https://github.com/google/gson/pull/2169
    • @deeptimarrivada1 made their first contribution in https://github.com/google/gson/pull/2192
    • @kb-1000 made their first contribution in https://github.com/google/gson/pull/2196
    • @BillyGalbreath made their first contribution in https://github.com/google/gson/pull/2213
    • @staale made their first contribution in https://github.com/google/gson/pull/2201

    Full Changelog: https://github.com/google/gson/compare/gson-parent-2.9.1...gson-parent-2.10

    Source code(tar.gz)
    Source code(zip)
  • gson-parent-2.9.1(Jul 31, 2022)

    • Make Object and JsonElement deserialization iterative rather than recursive (#1912)
    • Added parsing support for enum that has overridden toString() method (#1950)
    • Removed support for building Gson with Gradle (#2081)
    • Removed obsolete codegen hierarchy (#2099)
    • Add support for reflection access filter (#1905)
    • Improve TypeToken creation validation (#2072)
    • Add explicit support for float in JsonWriter (#2130, #2132)
    • Fail when parsing invalid local date (#2134)

    Also many small improvements to javadoc.

    Source code(tar.gz)
    Source code(zip)
  • gson-parent-2.9.0(Feb 11, 2022)

    The minimum supported Java version changes from 6 to 7.

    • Change target Java version to 7 (#2043)
    • Put module-info.class into Multi-Release JAR folder (#2013)
    • Improve error message when abstract class cannot be constructed (#1814)
    • Support EnumMap deserialization (#2071)
    • Add LazilyParsedNumber default adapter (#2060)
    • Fix JsonReader.hasNext() returning true at end of document (#2061)
    • Remove Gradle build support. Build script was outdated and not actively maintained anymore (#2063)
    • Add GsonBuilder.disableJdkUnsafe() (#1904)
    • Add UPPER_CASE_WITH_UNDERSCORES in FieldNamingPolicy (#2024)
    • Fix failing to serialize Collection or Map with inaccessible constructor (#1902)
    • Improve TreeTypeAdapter thread-safety (#1976)
    • Fix Gson.newJsonWriter ignoring lenient and HTML-safe setting (#1989)
    • Delete unused LinkedHashTreeMap (#1992)
    • Make default adapters stricter; improve exception messages (#2000)
    • Fix FieldNamingPolicy.upperCaseFirstLetter uppercasing non-letter (#2004)

    Thanks to our contributors, especially @Marcono1234!

    Source code(tar.gz)
    Source code(zip)
  • gson-parent-2.8.9(Oct 29, 2021)

    • Make OSGi bundle's dependency on sun.misc optional (#1993).
    • Deprecate Gson.excluder() exposing internal Excluder class (#1986).
    • Prevent Java deserialization of internal classes (#1991).
    • Improve number strategy implementation (#1987).
    • Fix LongSerializationPolicy null handling being inconsistent with Gson (#1990).
    • Support arbitrary Number implementation for Object and Number deserialization (#1290).
    • Bump proguard-maven-plugin from 2.4.0 to 2.5.1 (#1980).
    • Don't exclude static local classes (#1969).
    • Fix RuntimeTypeAdapterFactory depending on internal Streams class (#1959).
    • Improve Maven build (#1964).
    • Make dependency on java.sql optional (#1707).
    Source code(tar.gz)
    Source code(zip)
  • gson-parent-2.8.8(Aug 20, 2021)

    • Fixed issue with recursive types (#1390).
    • Better behaviour with Java 9+ and Unsafe if there is a security manager (#1712).
    • EnumTypeAdapter now works better when ProGuard has obfuscated enum fields (#1495).
    Source code(tar.gz)
    Source code(zip)
Owner
Google
Google ❤️ Open Source
Google
Convert Java to JSON. Convert JSON to Java. Pretty print JSON. Java JSON serializer.

json-io Perfect Java serialization to and from JSON format (available on Maven Central). To include in your project: <dependency> <groupId>com.cedar

John DeRegnaucourt 303 Dec 30, 2022
A simple java JSON deserializer that can convert a JSON into a java object in an easy way

JSavON A simple java JSON deserializer that can convert a JSON into a java object in an easy way. This library also provide a strong object convertion

null 0 Mar 18, 2022
MapNeat is a JVM library written in Kotlin that provides an easy to use DSL (Domain Specific Language) for transforming JSON to JSON, XML to JSON, POJO to JSON in a declarative way.

MapNeat is a JVM library written in Kotlin that provides an easy to use DSL (Domain Specific Language) for transforming JSON to JSON, XML to JSON, POJ

Andrei Ciobanu 59 Sep 17, 2022
Screaming fast JSON parsing and serialization library for Android.

#LoganSquare The fastest JSON parsing and serializing library available for Android. Based on Jackson's streaming API, LoganSquare is able to consiste

BlueLine Labs 3.2k Dec 18, 2022
Framework for serialization to Json, XML, Byte and Excel, therefore an oviparous wool milk sow J

NetworkParser Framework for serialization from Java objects to Json, XML and Byte. NetworkParser is a simple framework for serializing complex model s

Fujaba Tool Suite 4 Nov 18, 2020
JSON to JSON transformation library written in Java.

Jolt JSON to JSON transformation library written in Java where the "specification" for the transform is itself a JSON document. Useful For Transformin

Bazaarvoice 1.3k Dec 30, 2022
Generate Java types from JSON or JSON Schema and annotates those types for data-binding with Jackson, Gson, etc

jsonschema2pojo jsonschema2pojo generates Java types from JSON Schema (or example JSON) and can annotate those types for data-binding with Jackson 2.x

Joe Littlejohn 5.9k Jan 5, 2023
Essential-json - JSON without fuss

Essential JSON Essential JSON Rationale Description Usage Inclusion in your project Parsing JSON Rendering JSON Building JSON Converting to JSON Refer

Claude Brisson 1 Nov 9, 2021
A 250 lines single-source-file hackable JSON deserializer for the JVM. Reinventing the JSON wheel.

JSON Wheel Have you ever written scripts in Java 11+ and needed to operate on some JSON string? Have you ever needed to extract just that one deeply-n

Roman Böhm 14 Jan 4, 2023
A JSON Transmission Protocol and an ORM Library for automatically providing APIs and Docs.

?? 零代码、热更新、全自动 ORM 库,后端接口和文档零代码,前端(客户端) 定制返回 JSON 的数据和结构。 ?? A JSON Transmission Protocol and an ORM Library for automatically providing APIs and Docs.

Tencent 14.4k Dec 31, 2022
Text Object Java Objects (TOJOs): an object representation of a multi-line structured text file like CSV

It's a simple manager of "records" in a text file of CSV, JSON, etc. format. It's something you would use when you don't want to run a full database,

Yegor Bugayenko 19 Dec 27, 2022
A modern JSON library for Kotlin and Java.

Moshi Moshi is a modern JSON library for Android and Java. It makes it easy to parse JSON into Java objects: String json = ...; Moshi moshi = new Mos

Square 8.7k Dec 31, 2022
Sawmill is a JSON transformation Java library

Update: June 25, 2020 The 2.0 release of Sawmill introduces a breaking change to the GeoIpProcessor to comply with the updated license of the MaxMind

Logz.io 100 Jan 1, 2023
Genson a fast & modular Java <> Json library

Genson Genson is a complete json <-> java conversion library, providing full databinding, streaming and much more. Gensons main strengths? Easy to use

null 212 Jan 3, 2023
Lean JSON Library for Java, with a compact, elegant API.

mJson is an extremely lightweight Java JSON library with a very concise API. The source code is a single Java file. The license is Apache 2.0. Because

Borislav Iordanov 77 Dec 25, 2022
Elide is a Java library that lets you stand up a GraphQL/JSON-API web service with minimal effort.

Elide Opinionated APIs for web & mobile applications. Read this in other languages: 中文. Table of Contents Background Documentation Install Usage Secur

Yahoo 921 Jan 3, 2023
JSON Library for Java with a focus on providing a clean DSL

JSON Library for Java with a focus on providing a clean DSL

Vaishnav Anil 0 Jul 11, 2022
High performance JVM JSON library

DSL-JSON library Fastest JVM (Java/Android/Scala/Kotlin) JSON library with advanced compile-time databinding support. Compatible with DSL Platform. Ja

New Generation Software Ltd 835 Jan 2, 2023
A JSON Schema validation implementation in pure Java, which aims for correctness and performance, in that order

Read me first The current version of this project is licensed under both LGPLv3 (or later) and ASL 2.0. The old version (2.0.x) was licensed under LGP

Java Json Tools 1.5k Jan 4, 2023