Home > Net >  How to change json string to LinkedList when using fastjson in Java?
How to change json string to LinkedList when using fastjson in Java?

Time:05-27

I want to change the string into LinkedList,I write the code but it happen in to a exception,java.util.ArrayList cannot be cast to java.util.LinkedList,How to fix it?

LinkedList<String> names=new LinkedList<String>();
    names.add("a");
    names.add("b");
    String str=JSON.toJSONString(names);
    System.out.println(str);
    System.out.println((LinkedList<String>)JSON.parseArray(str,String.class));

CodePudding user response:

You can't cast an ArrayList to a LinkedList so you have to create a LinkedList. Try new LinkedList<String>(JSON.parseArray(str, String.class)). This creates a LinkedList containing all the elements of the JSON array. If the list does not have to be exactly a LinkedList, you can also try just using the List interface.

  • Related