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
Images grid JSON | Сетка изображений JSON

Images grid JSON | Сетка изображений JSON Задача Разработать приложение: Приложение должно получать JSON-список ссылок на изображения с сервера по адр

Sefo Notasi 2 Apr 25, 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 Jan 2, 2023
Manager of progress using Lottie JSON, compatible for Java and Kotlin.

Progress Lottie IGB Manager of progress using Lottie JSON, compatible for Java and Kotlin. Int Top In Bottom Important Info: To create a raw folder: R

Isaac G. Banda 21 Sep 16, 2022
Fast JSON parser for java projects

ig-json-parser Fast JSON parser for java projects. Getting started The easiest way to get started is to look at maven-example. For more comprehensive

Instagram 1.3k Dec 29, 2022
xls2json - Read in Excel file (.xls, .xlsx, .xlsm) and output JSON

xls2json Read in Excel file (.xls, .xlsx, .xlsm) and output JSON. Evaluates formulas where possible. Preserve type information from Excel via JSON typ

Tammo Ippen 39 Oct 19, 2022
Customizable JSON Schema-based forms for Kotlin and Compose

Kotlin JSON Forms Customizable JSON Schema-based forms for Kotlin and Compose This project aims to reimplement JSON Forms in Kotlin for use in Compose

Copper Leaf 3 Oct 1, 2022
A lightweight Kotlin DSL to render DSL style Json to String.

A lightweight Kotlin DSL to render DSL style Json to String.

null 4 May 5, 2021
Modern JSON processor with readable Kotlin syntax.

Kq Modern cross-platform JSON processor with readable Kotlin syntax. cat ~/Desktop/bdb.ndjson | kq '.filter{it.bool("muted")}.sortedBy{it.long("size")

Daniel Demidko 6 Jan 25, 2022
ktlint JSON Lines reporter

ktlint JSON Lines reporter Usage Download the jar and run: ktlint --reporter=jsonlines,artifact=ktlint-jsonlines-reporter.jar Download Either downloa

Anton Musichin 1 Nov 24, 2021
Generate a JSON bookmarks document from a GitHub user

Github to bookmarks This little webapp will generate a JSON bookmarks document from a GitHub user. This is intended to be used with bbt. An instance i

Benoit Lubek 2 Nov 8, 2021
A Shopping cart library for Android that allows you add to add items to cart and retrieve at ease using JSONObjects.

Carteasy A Shopping cart library for Android that allows you add to add items to cart and retrieve at ease using JSONObjects. Quick Start Add the foll

Tosin Onikute 25 Oct 19, 2022
Simple CLI app to convert XML retrieved from a configurable URI to JSON and back

XmlToJsonUtility Simple CLI app written in Kotlin (1.5.31) on Java 11, using Spring Boot. Queries a URI (default) as an XML source. Attempts to valida

Darius Washington 2 Oct 20, 2021
LiteHttp is a simple, intelligent and flexible HTTP framework for Android. With LiteHttp you can make HTTP request with only one line of code! It could convert a java model to the parameter and rander the response JSON as a java model intelligently.

Android network framework: LiteHttp Tags : litehttp2.x-tutorials Website : http://litesuits.com QQgroup : 42960650 , 47357508 Android网络通信为啥子选 lite-htt

马天宇 829 Dec 29, 2022
Speech-Text Converter is a simple task that enable the user to convert the speech to text or convert text to speech (by Mic)

Speech-Text Converter About Speech-Text Converter is a simple task that enable the user to convert the speech to text or convert text to speech (by Mi

Kareem Saeed 1 Oct 21, 2021
It's a simple app written in Kotlin that shows a simple solution for how to save an image into Firebase Storage, save the URL in Firestore, and read it back using Jetpack Compose.

It's a simple app written in Kotlin that shows a simple solution for how to save an image into Firebase Storage, save the URL in Firestore, and read it back using Jetpack Compose.

Alex 10 Dec 29, 2022
Convert OkHttp requests into curl logs.

Ok2Curl Convert OkHttp requests into curl logs. Usage Add library to project dependencies. Library is hosted on jcenter. repositories { jcenter()

Michal Moczulski 373 Jan 1, 2023
Convert your YouTube channel into a native Android app using YouTube Data API v3.

Convert your YouTube channel into an app. Screenshots • Description • Features • Configuration • Documentation Screenshots Description Channelify is a

Aculix Technologies LLP 121 Dec 26, 2022
Silky - Android application to convert videos from applications such as YouTube, Facebook, Twitter into audio (.mp3)

Silky Español (actualmente la app se encuentra en desarrollo ) Descripcion Aplic

null 2 Aug 24, 2022
A CLI tool to convert multi-module Jetpack Compose compiler metrics into beautiful HTML reports

A CLI tool to convert multi-module Jetpack Compose compiler metrics into beautiful HTML reports 1. What are Jetpack Compose compiler metrics? The Comp

Jaya Surya Thotapalli 116 Jan 3, 2023
Android Material Json Form Wizard is a library for creating beautiful form based wizards within your app just by defining json in a particular format.

Android Json Wizard Android Json Wizard is a library for creating beautiful form based wizards within your app just by defining json in a particular f

Vijay Rawat 355 Nov 11, 2022