Git Product home page Git Product logo

gson's Introduction

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.

Note

Gson is currently in maintenance mode; existing bugs will be fixed, but large new features will likely not be added. If you want to add a new feature, please first search for existing GitHub issues, or create a new one to discuss the feature and get feedback.

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.10.1'
}

Maven:

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

Gson jar downloads are available from Maven Central.

Build Status

Requirements

Minimum Java version

  • Gson 2.9.0 and newer: Java 7
  • Gson 2.8.9 and older: Java 6

Despite supporting older Java versions, Gson also provides a JPMS module descriptor (module name com.google.gson) for users of Java 9 or newer.

JPMS dependencies (Java 9+)

These are the optional Java Platform Module System (JPMS) JDK modules which Gson depends on. This only applies when running Java 9 or newer.

  • java.sql (optional since Gson 2.8.9)
    When this module is present, Gson provides default adapters for some SQL date and time classes.

  • jdk.unsupported, respectively class sun.misc.Unsafe (optional)
    When this module is present, Gson can use the Unsafe class to create instances of classes without no-args constructor. However, care should be taken when relying on this. Unsafe is not available in all environments and its usage has some pitfalls, see GsonBuilder.disableJdkUnsafe().

Minimum Android API level

  • Gson 2.11.0 and newer: API level 21
  • Gson 2.10.1 and older: API level 19

Older Gson versions may also support lower API levels, however this has not been verified.

Documentation

  • API Javadoc: Documentation for the current release
  • User guide: This guide contains examples on how to use Gson in your code
  • Troubleshooting guide: Describes how to solve common issues when using Gson
  • Releases and change log: Latest releases and changes in these versions; for older releases see CHANGELOG.md
  • 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, GitHub Discussions or the google-gson Google group to discuss Gson or to post questions.

Related Content Created by Third Parties

Building

Gson uses Maven to build the project:

mvn clean verify

JDK 11 or newer is required for building, JDK 17 is recommended. Newer JDKs are currently not supported for building (but are supported when using Gson).

Contributing

See the contributing guide.
Please perform a quick search to check if there are already existing issues or pull requests related to your contribution.

Keep in mind that Gson is in maintenance mode. If you want to add a new feature, please first search for existing GitHub issues, or create a new one to discuss the feature and get feedback.

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.

gson's People

Contributors

amogilev avatar capstan avatar degubi avatar dependabot[bot] avatar eamonnmcmanus avatar egor-n avatar elevne avatar ganadist avatar guptasourabh04 avatar hifromajay avatar igormiller avatar inder123 avatar jakewharton avatar joel-leitch avatar juandiana avatar lyubomyr-shaydariv avatar maicolantali avatar marcono1234 avatar mbrukman avatar mcumings avatar naturalwarren avatar nightlynexus avatar orischwartz avatar qwwdfsad avatar saiimons avatar sgbrown avatar superz2017 avatar swankjesse avatar williamcollishaw avatar yasirmhd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gson's Issues

http://groups.google.com/group/google-gson/t/677d56e9976d7761

Hi, guys!

I was thinking of the problem and have concluded, that the solution of the
issue (see link
http://groups.google.com/group/google-gson/t/677d56e9976d7761):
JsonObjectDeserializationVisitor should check if there is custom
deserializer registered for specified type and not create instance by.

  Something like this:

  @SuppressWarnings("unchecked")
  JsonObjectDeserializationVisitor(JsonElement json, Type type,
      ObjectNavigatorFactory factory, ObjectConstructor objectConstructor,
      TypeAdapter typeAdapter,
ParameterizedTypeHandlerMap<JsonDeserializer<?>> deserializers,
      JsonDeserializationContext context) {
    super(json, factory, objectConstructor, typeAdapter, deserializers,
context);
    JsonDeserializer deserialezer;
    if ((deserialezer = deserializers.getHandlerFor(type)) != null) {
      this.target = deserialezer.deserialize(json, type, context);
    } else {
      this.target = (T) objectConstructor.construct(type);
    }
  }


Original issue reported on code.google.com by [email protected] on 27 Aug 2008 at 7:57

Given sample does not work

When I include the given sample in my sourcecode I get an exception:

...
  class BagOfPrimitives {
    private int value1 = 1;
    private String value2 = "abc";
    private transient int value3 = 3;
  }
...
    BagOfPrimitives obj = new BagOfPrimitives();
    Gson gson = new Gson();
    String json = gson.toJson(obj); 
    // this throws an exception
    BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);  

Exception:

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: No-args
constructor for class InteropManager$BagOfPrimitives does not exist.
Register an InstanceCreator with Gson for this type to fix this problem.
    at
com.google.gson.MappedObjectConstructor.constructWithNoArgConstructor(MappedObje
ctConstructor.java:66)
    at
com.google.gson.MappedObjectConstructor.construct(MappedObjectConstructor.java:5
5)
    at
com.google.gson.JsonObjectDeserializationVisitor.<init>(JsonObjectDeserializatio
nVisitor.java:39)
    at
com.google.gson.JsonDeserializationContextDefault.fromJsonObject(JsonDeserializa
tionContextDefault.java:70)
    at
com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDeserializatio
nContextDefault.java:47)
    at com.google.gson.Gson.fromJson(Gson.java:326)
    at com.google.gson.Gson.fromJson(Gson.java:299)
    at InteropManager.getAObject(InteropManager.java:90)
    at MainForm.button1ActionPerformed(MainForm.java:49)
    at MainForm.access$3(MainForm.java:48)
    at MainForm$5.actionPerformed(MainForm.java:236)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

version: gson-1.1.1.jar
environment: eclipse 3.3.2

Original issue reported on code.google.com by [email protected] on 11 Aug 2008 at 9:14

Map serialization fails

What steps will reproduce the problem?
1. new Gson().toJson(new HashMap<String, String>());

What is the expected output?
{}

What do you see instead?
Fails with the attached exception.

What version of the product are you using? On what operating system?
gson 1.1.1
JDK 1.5, JDK 1.6

Please provide any additional information below.


Original issue reported on code.google.com by [email protected] on 30 Jul 2008 at 9:57

Attachments:

Pretty Print generates invalid JSON

Version: 1.2

The following code returns an invalid JSON string:

-----

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class App {
    public static void main(String[] args) {
        Node root = new Node("root");
        root.createChild("Pete");

        Gson gson = new GsonBuilder()
                .setPrettyPrinting()
                .create();

        System.out.println(gson.toJson(root));
    }
}

class Node {
    private final String name;
    private final List<Node> children = new ArrayList<Node>();

    public Node(String name) {
        this.name = name;
    }

    public Node createChild(String childName) {
        Node child = new Node(childName);
        children.add(child);
        return child;
    }
}

Original issue reported on code.google.com by [email protected] on 27 Sep 2008 at 5:54

Gson should provide an ability to restrict the namespace of classes used

It should be possible to restrict Gson to only java.*, javax.* and
com.google.checkout.api.model.* and nothing else. 

This is probably a good security feature. We should look at Ant (or
eclipse) conventions for deciding how to define package mappings. 

Original issue reported on code.google.com by inder123 on 22 May 2008 at 5:52

StackOverflowError for big String values (JSON to Java)

import com.google.gson.Gson;
public class TestGson {

  public static void main(String[] args) {
    String str = getJsonString(Integer.parseInt(args[0]));
    GString gString = new Gson().fromJson(str, GString.class);
  }

  public static String getJsonString(int size) {
    StringBuilder builder = new StringBuilder();
    builder.append("{\"value\":\"");
    for (int i = 0; i <= size; i++) {
      builder.append("a");
    }
    builder.append("\"}");
    return builder.toString();
  }

}

public class GString {

  private String value = null;

  public String getValue() {
    return value;
  }

}

This will always end in an StackOverflowError for big Strings (e.g. 6112) 
at line 303 in JsonParser.java.

Original issue reported on code.google.com by [email protected] on 22 Sep 2008 at 12:33

Not serializing arrays of string

What steps will reproduce the problem?

Try to serialize and array of String

What is the expected output? What do you see instead?

["hello", "world"]
[{},{}]

What version of the product are you using? On what operating system?

Current.  Ubuntu ;)

Please provide any additional information below.

it isn't serializing my array list of strings as it once was, I just get a
list of empty dicts of the same size.

For example the output of :

import com.google.gson.Gson;
import java.util.List;
import java.util.ArrayList;

public class GsonExample {

  public static void main(String args[]) {
    List<String> vals = new ArrayList<String>();
    vals.add("Hello");
    vals.add("World");
    Gson gson = new Gson();
    System.out.println(gson.toJson(vals));
    System.out.println(gson.toJson(vals, List.class));
  }
}

Is :

[{},{}]
[{},{}]

At line 127 of JsonSerializationVisitor the fieldValue of my object is
"ade" for instance and the fieldType is "class java.lang.Object"

At line 131, the childVisitor.getJsonElement() line always returns an empty
dict {}

Regards,

Cameron

Original issue reported on code.google.com by [email protected] on 7 May 2008 at 6:21

Gson does not handle null values in arrays properly

(reported by Ben Littman)
This:
    System.out.println(gson.toJson(new String[]{"foo", "bar"}));
results in:
["foo", "bar]

But should a null value be allowed, as in:
    System.out.println(gson.toJson(new String[]{"foo", null,"bar"}));
which results in:
java.lang.NullPointerException
        at
com.google.gson.JsonTreeNavigator.visitChild(JsonTreeNavigator.java:76)
        at
com.google.gson.JsonTreeNavigator.navigate(JsonTreeNavigator.java:39)
        at
com.google.gson.JsonCompactFormatter.format(JsonCompactFormatter.java:112)
        at com.google.gson.Gson.toJson(Gson.java:270)
        at com.google.gson.Gson.toJson(Gson.java:243)

Also, this:
    String[] stringArray = gson.fromJson("[\"foo\", \"bar\"]", String[].class);
returns the string array one would expect

But an serialized array with a null in it:
    String[] stringArray = gson.fromJson("[\"foo\", null, \"bar\"]",
String[].class);
results in:
java.lang.IllegalState
Exception
        at
com.google.gson.JsonArrayDeserializationVisitor.visitArray(JsonArrayDeserializat
ionVisi
tor.java:73)
        at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:136)
        at
com.google.gson.JsonDeserializationContextDefault.fromJsonArray(JsonDeserializat
ionCont
extDefault.java:63)
        at
com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDeserializatio
nContex
tDefault.java:45)
        at com.google.gson.Gson.fromJson(Gson.java:319)
        at com.google.gson.Gson.fromJson(Gson.java:292)

Original issue reported on code.google.com by inder123 on 26 Jun 2008 at 7:38

Add toString() to Gson

Gson should provide a convenient toString() that displays the type-handlers 
that have been registered alongwith any other configuration settings.

Original issue reported on code.google.com by inder123 on 15 Sep 2008 at 3:54

Less strict parsing to make it easier to switch to gson?

gson appears to require all the elements to be strictly quoted. e.g. it
wants the format: { "hello": "world" }. Some other libraries like
net.sf.json and org.json are more relaxed and will also accept { hello:
"world" } but gson doesn't seem to accept this.

For example, the json.org api doc says: "Strings do not need to be quoted
at all if they do not begin with a quote or single quote, and if they do
not contain leading or trailing spaces, and if they do not contain any of
these characters: { } [ ] / \ : , = ; # and if they do not look like
numbers and if they are not the reserved words true, false, or null."

http://www.json.org/javadoc/org/json/JSONObject.html

It's arguable whether this behaviour is sensible / in spec, but to switch
to gson from my current library I'll have to change all my unit tests,
notify everyone who interacts with me that they may have to review / change
their JSON formatting etc etc. and cope with any resulting breakages.

Could more relaxed parsing behaviour be made an option maybe via an
alternate javacc parser?

Original issue reported on code.google.com by [email protected] on 8 Sep 2008 at 1:05

Custom Serializers fail if the serializer context is used on the source

Gson will fail to serialize a class "Foo" if you create a custom serializer
as follows:

public static class FooTypeAdapter implements JsonSerializer<Foo> {
  public JsonElement serialize(Foo src, Type typeOfSrc,
JsonSerializationContext context) {
    return context.serialize(src, typeOfSrc);
  }
}

Basically, it detects this as a circular reference.  Instead, we should
allow this kind of custom serializer because a client may want to perform
the default serialization of an object and then add new fields into the
JsonElement tree.

For example:
public static class FooTypeAdapter implements JsonSerializer<Foo> {
  public JsonElement serialize(Foo src, Type typeOfSrc,
JsonSerializationContext context) {
    JsonElement element = context.serialize(src, typeOfSrc);
    JsonObject jsonObject = element.getAsJsonObject();
    jsonObject.add("someNewProperty", new JsonPrimitive(1L));
    return jsonObject;
  }
}

Original issue reported on code.google.com by [email protected] on 14 Sep 2008 at 7:53

Provide support for pretty printing

Gson should provide ability to print nicely indented Json. It should be
possible to set print margin, default indentation, and so on. 

Original issue reported on code.google.com by inder123 on 25 Apr 2008 at 9:10

Add support for java.math.BigDecimal

JsonPrimitive provides support to get values as double through
getAsDouble(). However, to support higher precision (for example, while
dealing with money objects), it should also provide support for BigDecimal. 

Original issue reported on code.google.com by inder123 on 18 Aug 2008 at 8:47

Update Documentation

Update the "User Guide" to reflect the new features that have been added to
GSON since its initial launch.

Here is a list of some of the features:
- Field Naming Policy including the new "SerializedName" annotation
- Null Field Support (coming in 1.2)
- Reader and Writer support (coming in 1.2)

Original issue reported on code.google.com by [email protected] on 31 Jul 2008 at 1:08

Can not parse null arrays

What steps will reproduce the problem?
1. JSON to parse: 
2. Java: class Test { Object[] my_array; }
3. gson.fromJson("{\"my_array\": null}", Test.class);

What is the expected output? What do you see instead?

Expected: A Test object with my_array initialized to null.
Actual: java.lang.NullPointerException
        at
com.google.gson.JsonDeserializationVisitor.visitChildAsArray(JsonDeserialization
Visitor.java:93)
        at
com.google.gson.JsonObjectDeserializationVisitor.visitArrayField(JsonObjectDeser
ializationVisitor.java:114)
        at
com.google.gson.ObjectNavigator.navigateClassFields(ObjectNavigator.java:172)
        at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:152)
        at
com.google.gson.JsonDeserializationContextDefault.fromJsonObject(JsonDeserializa
tionContextDefault.java:75)
        at
com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDeserializatio
nContextDefault.java:47)
        at com.google.gson.Gson.fromJson(Gson.java:310)
        at com.google.gson.Gson.fromJson(Gson.java:285)

What version of the product are you using? On what operating system?

v1_0 on Linux

Original issue reported on code.google.com by [email protected] on 2 Jun 2008 at 11:52

Support JavaBeans properties in addition to class fields

Gson uses class fields for conversion to/from Json. It would also be great
to have a mode of operation (using GsonBuilder) that forces Gson to use
methods as well. Essentially, a mode where Gson only considers the class
members with @Expose annotation.

Original issue reported on code.google.com by inder123 on 27 Apr 2008 at 2:37

Provide support to escape HTML

To prevent against XSS attacks, Gson should provide a GsonBuilder option to
automatically escape and unescape HTML

Original issue reported on code.google.com by inder123 on 25 Apr 2008 at 11:18

Provide annotation to rename an individual field

I'd like the ability to control the name of a property being serialized on
a per-field basis using an annotation. Something like:

   @SerializeAsName("id")
   String getUniqueName() { ... }

Other alternatives are @Name, @Named, @JsonName, etc.

Original issue reported on code.google.com by [email protected] on 4 Jun 2008 at 10:09

Edit User Guide to match 1.0 APIs

API changed in the 1.0 release, and the guides are not yet updated to match
them. Also, publish the guides on the wiki for gson.

Original issue reported on code.google.com by inder123 on 29 May 2008 at 4:10

Gson should limit the allowed recursion depth

(reported by Meder) While parsing untrusted JSON, or even during attempting
to serialize classes, Gson should consider limiting the maximum allowed
depth for recursion. There should also be an option in GsonBuilder to set a
different value.

Original issue reported on code.google.com by inder123 on 8 Jul 2008 at 5:43

Fails to serialize/deserialize a class where a super-class has a type parameter

Unfortunately, shortly after the Gson 1.2 release, I found a bug in the
TypeVariable support.  Basically, the following class can not be serialized
or deserialized using Gson:

public class Foo<T> {
  private final T someField;

  public Foo(T value) {
    this.someField = value;
  }

  public boolean equals(Object o) {
    if (!(o instanceof Foo)) {
      return false;
    } else {
        return someField.equals(((Foo)o).someField);
    }
  }
}

public class Bar extends Foo<Integer> {
  public Bar(Integer i) {
    super(i);
  }
}

Gson gson = new Gson();
Bar bar1 = new Bar(1);
String json = gson.toJson(bar1);   // Fails
Bar bar2 = gson.fromJson("{\"someField\":1", Bar.class);    // Fails

assertEquals(bar1, bar2);

Original issue reported on code.google.com by [email protected] on 29 Aug 2008 at 11:53

Provide support to escape " character

if i have a property set to "aaaa\"bbbb" json loooks like "aaaa"bbbb". The
output should be properly escaped. 

Original issue reported on code.google.com by inder123 on 19 May 2008 at 6:19

Support Readers and Writers for Gson

To support streaming input/output it should be possible to invoke toJson
with a writer, and fromJson with a Reader. 

Original issue reported on code.google.com by inder123 on 8 Jul 2008 at 5:46

JSON does not seem to support the java.util.Date type

What steps will reproduce the problem?
Sample code:
Gson gson = new Gson();
Date test = new Date();
System.out.println("Date is "+gson.toJson(test));

What is the expected output? What do you see instead?
Expected output was a json string with current date. Instead
Date is {}      (an empty javascript object)

What version of the product are you using? On what operating system?
gson-1.1.1. Mac OS X, JDK 5

Please provide any additional information below.
I modified my code to pass dates as Strings. But this is not elegant.


Original issue reported on code.google.com by [email protected] on 5 Aug 2008 at 4:30

toJson inserts extraneous comma in Collection elements with pretty-printing turned on

What steps will reproduce the problem?
1. Compile and run the attached test case

What is the expected output? What do you see instead?

Expected:

xxx{"x":"hello","y":"world"}xxx
xxx[{"x":"hello","y":"world"}]xxx
xxx{"x":"hello","y":"world"}
xxx
xxx[{"x":"hello","y":"world"}]
xxx

Actual:

xxx{"x":"hello","y":"world"}xxx
xxx[{"x":"hello","y":"world"}]xxx
xxx{"x":"hello","y":"world"}
xxx
xxx[{,"x":"hello","y":"world"}]
xxx
Exception in thread "main" com.google.gson.JsonParseException: Failed
parsing JSON source: java.io.StringReader@860d49 to Json
    at com.google.gson.Gson.fromJson(Gson.java:383)
    at com.google.gson.Gson.fromJson(Gson.java:326)
    at PPTest.main(PPTest.java:39)
Caused by: com.google.gson.ParseException: Encountered "," at line 1, column 3.
Was expecting one of:
    "\"" ...
    "}" ...

    at com.google.gson.JsonParser.generateParseException(JsonParser.java:497)
    at com.google.gson.JsonParser.jj_consume_token(JsonParser.java:436)
    at com.google.gson.JsonParser.JsonObject(JsonParser.java:57)
    at com.google.gson.JsonParser.JsonValue(JsonParser.java:141)
    at com.google.gson.JsonParser.Elements(JsonParser.java:117)
    at com.google.gson.JsonParser.JsonArray(JsonParser.java:103)
    at com.google.gson.JsonParser.parse(JsonParser.java:25)
    at com.google.gson.Gson.fromJson(Gson.java:375)
    ... 2 more


What version of the product are you using? On what operating system?

Gson 1.2 with Sun Java 1.6.0_07 (Ubuntu package sun-java6-jdk=6-07-3ubuntu2

Please provide any additional information below.


Original issue reported on code.google.com by [email protected] on 28 Sep 2008 at 9:00

Attachments:

Read and write log files where each entry is in JSON format

Perhaps Gson would be useful for reading and writing logs where each entry
is in JSON format?

I haven't looked closely, but it appears that Gson won't emit a newline
when serializing to a file.  If this is something that Gson could
guarantee, then we could use newlines as record separators and make each
log entry a JSON object, and also use GSon to iterate over a log file and
deserialize each line into an object.

Original issue reported on code.google.com by bslesinsky on 15 Aug 2008 at 3:39

Add a ZIP download

We should add a ZIP file as a download which includes the license, jar and
README for Gson.

Original issue reported on code.google.com by [email protected] on 3 Jun 2008 at 5:51

Json + schema

http://groups.google.com/group/json-schema/web/json-schema-proposal---second-dra
ft
has a discussion on how to define a Json schema. We should explore how this
can be used for Gson. In Gson, currently, the Java classes define the
schema. May be we can provide a validator that validates the schema against
a set of classes.Or generates the Json schema corresponding to a set of
classes (using the ObjectNavigator). 

Original issue reported on code.google.com by inder123 on 13 Jun 2008 at 8:46

java.lang.IllegalArgumentException when giving a double in place of a String

What steps will reproduce the problem?

Try to parse {"version": 1.0} into class A { String version; }

What is the expected output? What do you see instead?

I expect a JsonParsingException, but instead get:

java.lang.IllegalArgumentException: Can not adapt type class java.lang.Double 
to class 
java.lang.String
    at com.google.gson.PrimitiveTypeAdapter.adaptType(PrimitiveTypeAdapter.java:64)
    at com.google.gson.TypeAdapterNotRequired.adaptType(TypeAdapterNotRequired.java:51)
    at 
com.google.gson.JsonObjectDeserializationVisitor.visitPrimitiveField(JsonObjectD
eserializationVis
itor.java:131)
    at com.google.gson.ObjectNavigator.navigateClassFields(ObjectNavigator.java:177)
    at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:152)
    at 
com.google.gson.JsonDeserializationContextDefault.fromJsonObject(JsonDeserializa
tionContextD
efault.java:75)
    at 
com.google.gson.JsonDeserializationContextDefault.deserialize(JsonDeserializatio
nContextDefaul
t.java:47)
    at com.google.gson.Gson.fromJson(Gson.java:326)
    at com.google.gson.Gson.fromJson(Gson.java:299)

What version of the product are you using? On what operating system?
v1_1 on Linux

Please provide any additional information below.


Original issue reported on code.google.com by [email protected] on 29 Jul 2008 at 10:21

GsonBuilder.prettyPrint causes extra element when serializer returns JsonArray

What steps will reproduce the problem?
1. Run the attached unit test

What is the expected output? What do you see instead?
 was expecting "[1,2,3,4,5]" and got "[,1,2,3,4,5]"

What version of the product are you using? On what operating system?
 GSON 1.1.1, Windows XP, Java 1.6.0_04

Please provide any additional information below.
 If I don't call setPrettyPrint, the unit test passes.  (Sorry if this
report came in twice, Google barfed the first time I tried to submit it)

Original issue reported on code.google.com by [email protected] on 23 Jul 2008 at 8:30

Attachments:

Gson should support serialization of nulls

See:
http://groups.google.com/group/google-gson/browse_thread/thread/48a2ce8b9cc2d7ee

We should consider supporting a GsonBuilder mode to send out nulls as well. 

Original issue reported on code.google.com by inder123 on 29 Jul 2008 at 12:30

Gson fails to parse strings with chinese characters

Gson fails to parse: 

{"name": "好", "code": "aa", "remark": "aa"}

gson.fromJson(jsonString, TbDepartment.class);

的时候出现异常 Failed parsing JSON source: {"name": "好", "code": "aa",
"remark": "aa"} to Json 

See:
http://groups.google.com/group/google-gson/browse_thread/thread/588a87b9ef1fc479

Original issue reported on code.google.com by inder123 on 29 Jul 2008 at 12:28

Serializing/Deserializing simple maps should be better supported

Attempting to simply serialize a map results in fairly useless output:

// dead simple map
Map<String, Object> m = new ArrayOrderedMap<String, Object>();
m.put("id", 123);
m.put("thing", "AZ");

// serialize (annoyingly requires the typetoken thing)
String encoded = gson.toJson(data, new TypeToken<Map<String, Object>>()
{}.getType());

encoded = {"id":{},"thing":{}}

It should have been:
encoded = {"id":123,"thing":"AZ"}

This should really be able to handle the simple example of a map of
primitive/simple objects much better. The same type of thing happens when
attempting to read back in the data.

With a more realistic example it is even worse because another map placed
inside the first map results in an exception like so:
com.google.gson.JsonParseException: The JsonSerializer
com.google.gson.DefaultTypeAdapters$MapTypeAdapter@b27bb5 failed to
serialized object {name=aaron, date=Mon Sep 15 11:58:33 BST 2008, num=456,
array=[Ljava.lang.String;@fe3238} given the type class java.lang.Object
    at
com.google.gson.JsonSerializerExceptionWrapper.serialize(JsonSerializerException
Wrapper.java:61)
    at
com.google.gson.JsonSerializationVisitor.visitUsingCustomHandler(JsonSerializati
onVisitor.java:177)
    at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:144)
    at
com.google.gson.JsonSerializationContextDefault.serialize(JsonSerializationConte
xtDefault.java:47)
    at
com.google.gson.DefaultTypeAdapters$MapTypeAdapter.serialize(DefaultTypeAdapters
.java:301)
    at
com.google.gson.DefaultTypeAdapters$MapTypeAdapter.serialize(DefaultTypeAdapters
.java:293)
    at
com.google.gson.JsonSerializerExceptionWrapper.serialize(JsonSerializerException
Wrapper.java:48)
    at
com.google.gson.JsonSerializationVisitor.visitUsingCustomHandler(JsonSerializati
onVisitor.java:177)
    at com.google.gson.ObjectNavigator.accept(ObjectNavigator.java:144)
    at
com.google.gson.JsonSerializationContextDefault.serialize(JsonSerializationConte
xtDefault.java:47)
    at com.google.gson.Gson.toJson(Gson.java:272)
    at com.google.gson.Gson.toJson(Gson.java:228)
    at
org.sakaiproject.entitybroker.impl.EntityEncodingManager.encodeData(EntityEncodi
ngManager.java:586)
    at
org.sakaiproject.entitybroker.impl.EntityEncodingManagerTest.testEncode(EntityEn
codingManagerTest.java:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.jav
a:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at junit.framework.TestCase.runTest(TestCase.java:154)
    at junit.framework.TestCase.runBare(TestCase.java:127)
    at junit.framework.TestResult$1.protect(TestResult.java:106)
    at junit.framework.TestResult.runProtected(TestResult.java:124)
    at junit.framework.TestResult.run(TestResult.java:109)
    at junit.framework.TestCase.run(TestCase.java:118)
    at junit.framework.TestSuite.runTest(TestSuite.java:208)
    at junit.framework.TestSuite.run(TestSuite.java:203)
    at
org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestR
eference.java:130)
    at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner
.java:460)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner
.java:673)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java
:386)
    at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.jav
a:196)
Caused by: java.lang.IllegalArgumentException: Map objects need to be
parameterized unless you use a custom serializer. Use the
com.google.gson.reflect.TypeToken to extract the ParameterizedType.
    at com.google.gson.TypeInfoMap.<init>(TypeInfoMap.java:34)
    at
com.google.gson.DefaultTypeAdapters$MapTypeAdapter.serialize(DefaultTypeAdapters
.java:298)
    at
com.google.gson.DefaultTypeAdapters$MapTypeAdapter.serialize(DefaultTypeAdapters
.java:293)
    at
com.google.gson.JsonSerializerExceptionWrapper.serialize(JsonSerializerException
Wrapper.java:48)
    ... 31 more



Original issue reported on code.google.com by azeckoski on 15 Sep 2008 at 11:00

Exception Handling for Custom Serializers

We should add some exception handling around the "custom" type adapters to
ensure that all exceptions that are propagated out from the "toJson" and
"fromJson" are JsonParseException.

Original issue reported on code.google.com by [email protected] on 22 Aug 2008 at 6:09

Provide some benchmarking results

We should implement some benchmarking to ensure that with each release we
are not degrading on performance.  Maybe we should start with the next
release (i.e. 1.2) as the base benchmark.

Original issue reported on code.google.com by [email protected] on 17 Aug 2008 at 12:29

Provide default support for java.util.Map

Should be able to convert the default representation of a Map. 
Should be able to deserialize {{"a":"1"},{"b":2"}} as well as
[{"a":"1"},{"b":2"}] to a map. Consider using a concrete implementation
(linked list) of Map that preserves the order of elements. 

Original issue reported on code.google.com by inder123 on 25 Apr 2008 at 7:16

Gson should provide an ability to customize field name mapping

Currently Gson just uses the actual name of the field as the Json property
name. This should be customizable. For example, it should be possible to
convert camel-case into hyphenated, or Camel-cased with upper-case first
letter.

so, myFavoriteField in Java gets mapped to my-favorite-field or
MyFavoriteField in Json. 

One approach to achieve this is by providing a name translation policy in
GsonBuilder. 

Original issue reported on code.google.com by inder123 on 22 May 2008 at 5:51

Using excludeFieldsWithoutExposeAnnotation can write empty objects

What steps will reproduce the problem?
1. Build a Gson object using GsonBuilder.excludeFieldsWithoutExposeAnnotation()
2. Annotate a class variable with @Expose
3. Write an instance of the class with the variable that was exposed null

What is the expected output? What do you see instead?
I expected to see nothing written for that object, since it should be
empty, instead, I see an empty object.

What version of the product are you using? On what operating system?
1.1.1

Please provide any additional information below.
I have attached a unit test that demonstrates this issue.

Original issue reported on code.google.com by [email protected] on 6 Aug 2008 at 6:16

Attachments:

Publish Gson jars in maven2 repository

The subject says it all. We should figure out how guice guys are doing it,
and do the same. 

Original issue reported on code.google.com by inder123 on 30 May 2008 at 10:00

Gson should support Wildcard types

We should add support for Wildcard fields where it is "extending" some
object.  For example:

public class Foo {
  private static final List<? extends Number> EMPTY_LIST = Collections.
  private final List<? extends Number> listOfNumbers;

  public Foo() {
    this(null);
  }

  public Foo(List<? extends Number> list) {
    this.listOfNumbers = list;
  }
}

Original issue reported on code.google.com by [email protected] on 28 Aug 2008 at 8:14

Custom Deserializers fail if the deserializer context is used on the source JsonElement

Gson gets caught in infinite recursion if a client attempts to convert a
JSON string into a Java object of type Foo with the following
JsonDeserializer registered:

public static class FooTypeAdapter implements JsonDeserializer<Foo> {
  public Foo deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
      throws JsonParseException {
    Foo fooObj = context.deserialize(json, typeOfT);
    fooObj.setExtraField("ThisIsExtra");
    return fooObj;
  }
}

Original issue reported on code.google.com by [email protected] on 14 Sep 2008 at 7:58

  • Merged into: #43

publish javadocs on the web

Probably best to check them in the svn alongwith setting properties to
enable them to be viewed as HTML. 

Original issue reported on code.google.com by inder123 on 29 May 2008 at 4:09

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.