JamesDeCarlo / google-gson

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

Strange example in the user guide #361

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
The user guide shows this example:

List<String> myStrings = new List<String>();
gson.toJson(myStrings); // Will cause a runtime exception

gson.fromJson(json, myStrings.getClass());

This example has a few issues.
1.) List is an interface and does not have a constructor.  (Not a big deal, but 
I figured I should mention it.)
2.) The `json` and the `gson` variables are undefined.  (I assume the second 
line is supposed to define and initialize the value of `json`.)
3.) Even if you correct these mistakes, this code does not throw a runtime 
exception. (But the comment in the exmaple insists that it will.)  For example:

import java.util.*;
import com.google.gson.*;

public class Test
{
    public static void
    main(String[] args)
    {        
        Gson gson = new Gson();
        List<String> myStrings = new ArrayList<String>();
        String json = gson.toJson(myStrings); // Will cause a runtime exception
        Object ans = gson.fromJson(json, myStrings.getClass());

        System.out.println(ans);
        /*
            expected output:
                runtime exception (according to the user guide)

            actual output:
                []
        */
    }
}

Original issue reported on code.google.com by von...@gmail.com on 31 Aug 2011 at 5:08

GoogleCodeExporter commented 9 years ago
Thanks for reporting the mistakes. I have corrected them. 
A very early version of Gson (1.x) was unable to handle any type of list 
without type parameter for toJson(). The newer versions of Gson would actually 
be able to handle a list of primitives just fine.

Original comment by inder123 on 16 Dec 2011 at 6:20