简体   繁体   中英

Convert JSON string back to Java List

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
    }

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

尝试这个

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM