3

I am using gson to convert a List to a JSON string and back to List.I am getting a ClassCastException while converting the objects in the list back to string.I would be grateful for any assistance.

public void JSONTest()    
{

    List<String> list=new ArrayList();
    list.add("a");
    list.add("b");
    list.add("c");
    System.out.println(list);
    Gson gsonSender = new Gson();
    String json = gsonSender.toJson(list);
    System.out.println(json);
    Gson gsonReceiver = new Gson();
    List obj = gsonReceiver.fromJson(json, List.class);
    Iterator it=obj.iterator();
    while(it.hasNext())
    {
        System.out.println((String)it.next());//java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.String
    }

}
0

2 Answers 2

8
Type type = new TypeToken<List<String>>(){}.getType();
 List<String> obj = gsonReceiver.fromJson(json,type);

Type is from java.lang.reflect.Type and TypeToken is from com.google.gson.reflect.TypeToken.

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

1 Comment

What is this syntax: {} after Type type = new TypeToken<List<String>>()
0

Try this

List<String> obj = gsonReceiver.fromJson(json, List.class);

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.