0
        List<Object> l = new ArrayList<Object>();
        l.add("abc");
        String s = (String) l.get(0); /////// No Exception here
        System.out.println(l); 
        String json = gson.toJson(l);
        System.out.println(json);
        Type t = new TypeToken<List<Object>>() {
        }.getType();
        List<Object> dl = gson.fromJson(json, t);
        String ds = (String) dl.get(0); /////Class Cast Exception here

Doing something like the above one. I am trying to serialize a list of Objects. First element in that is a String, but when I deserialized the list and reading the first element to a string it's throwing a classcastexception. And there are no exceptions when reading the first element to a string before serializing.

What's the reason behind this?

5
  • 2
    Have you stepped through this code line-by-line to see what might be gling on? Commented Apr 19, 2015 at 14:01
  • 1
    Give the EXACT and COMPLETE error message. And show us the JSON. Commented Apr 19, 2015 at 14:41
  • This is the error message:Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String Commented Apr 19, 2015 at 17:01
  • If you have an Object, that did not come from JSON. (Unless GSON uses Object as a "null" value or some such -- I'm not up on all the various JSON kits and their quirks.) Again, where is the JSON? Commented Apr 20, 2015 at 19:08
  • I don't get any error when running this code. Which version of Gson are you using? Commented Apr 21, 2015 at 10:19

1 Answer 1

1

I have an older version of GSON 1.4.

Updating it to 2.2.4 version worked.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.