FranzGames / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Deserializing of custom object collection (comma issue) #401

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?

1. The code:
 items = gson.fromJson(json, new TypeToken<ArrayList<Foo>>(){}.getType());

2. The data:
[
 {"uuid":"041347d3-56b5-4f64-b295-044d812802a3", "path":"fooPath", "name":"FooName"},
]

What is the expected output? 

  ArrayList of Foo with size = 1.

What do you see instead?

  ArrayList of Foo with size = 2.

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

  gson-2.1, Android 3.1

Please provide any additional information below.

  The comma (,) symbol after the (}) causes trouble. If I remove the comma - the resulting array is correct.

Original issue reported on code.google.com by martynas...@gmail.com on 12 Jan 2012 at 2:10

GoogleCodeExporter commented 9 years ago
Unnecessary commas aren't valid JSON. Gson supports them when you're 
databinding because it's lenient by default. Here's what JsonReader says on it:

  "Setting the parser to lenient causes it to ignore the following syntax errors:
   ... Unnecessary array separators. These are interpreted as if null was the omitted value."

http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/s
tream/JsonReader.html#setLenient(boolean)

Your best bet is to avoid the avoid unnecessary commas in your documents. 
Usually machine-generated JSON won't have them.

Original comment by limpbizkit on 12 Jan 2012 at 3:58

GoogleCodeExporter commented 9 years ago
Could you kindly reconsider this?

When writing the json manually (what I do quite often as I use it for 
configuration)
the trailing comma bites me quite often. Lenient mode doesn't help here at all 
as the null leads to worse problems later.

Note that both Java and Javascript allow and IGNORE trailing commas in array 
initializers, see
http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.6
http://ecma262-5.com/ELS5_HTML.htm#Section_11.1.5
Maybe one day JSON will too as it's very practical.

In most browsers "[1,, 2,]" is the same as "[1, null, 2]", since the trailing 
comma gets ignored and only the others get interpreted as nulls.

The needed change is very trivial (just drop the condition above the comment 
`fall-through to handle ",]"`).

Original comment by Maaarti...@gmail.com on 29 Jul 2012 at 8:58