1

I have the following string : ["LankaBell","BillDesk"]

How can i convert it to Java List Object using using json-lib-2.2.3-jdk15.jar\net\sf\json library ?

EDIT : If not possible using this library then solution using other libraries is also appreciated.

Prateek
  • 12,014
  • 12
  • 60
  • 81

5 Answers5

5

Using the json-lib:

String source = "[\"LankaBell\",\"BillDesk\"]";
List<String> list = new ArrayList<>();
list = JSONArray.toList(JSONArray.fromObject(source), new Object(), new JsonConfig());

(Actually you can use just JSONArray.toList(JSONArray.fromObject(source)) but it is deprecated)

Another non-deprecated solution:

list = (List<String>) JSONArray.toCollection(JSONArray.fromObject(source))
Yurii Shylov
  • 1,219
  • 1
  • 10
  • 19
  • Thanks it works for me using the same library(net.sf.json..). i use this approach : list = (List) JSONArray.toCollection(JSONArray.fromObject(source)) – Prateek Aug 13 '13 at 05:06
  • Thanks Shylov. It worked. –  Feb 04 '16 at 15:01
2

I highly recommend using Jackson instead of json-lib.

List<String> list = new org.codehaus.jackson.map.ObjectMapper().readValue("[\"LankaBell\",\"BillDesk\"]", List.class);
superEb
  • 5,613
  • 35
  • 38
  • I +1'd you, but you should really use the example with a generic Type for this. You are not guaranteed to get a List with your example! – Tom Carchrae Aug 12 '13 at 15:16
  • Good point, @TomCarchrae. I assumed it would be safe enough for the array in question though. Obviously my code is not ideal (e.g. `ObjectMapper` should probably be reused, checked exceptions need to be handled, using parameterized type with casting issues might not be desirable vs using raw type, value to be deserialized would probably be a variable, etc), but it's a quick snippet of how easy it is to use Jackson. – superEb Aug 12 '13 at 15:32
2
String input = "[\"LankaBell\",\"BillDesk\"]";

// net.sf.json.JSONArray
JSONArray jsonArray = JSONArray.fromObject(input);

List<String> list = new ArrayList<String>();

for (Object o : jsonArray) {
    list.add((String) o);
}

log.debug(list);
daveloyall
  • 2,140
  • 21
  • 23
  • @Yurii Shylov put more work into [his answer](http://stackoverflow.com/questions/18190001/how-to-convert-json-string-with-square-brackets-to-list/18190569#answer-18190382); his answer is superior. – daveloyall Aug 12 '13 at 15:13
  • Thanks daveloyall for redirecting to Yurii solution;+1 for your honesty – Prateek Aug 13 '13 at 05:08
0
    String string = "[\"LankaBell\",\"BillDesk\"]";

    //Remove square brackets
    string = string.substring(1, string.length()-1);

    //Remove qutation marks
    string.replaceAll("\"", "");

    //turn into array
    String[] array = string.split(",");

    //Turn into list
    List<String> list = Arrays.asList(array);

    System.out.println(list);
Brinnis
  • 906
  • 5
  • 12
0
Object[] objs = "[\"Lankabell\", \"BillDesk\"]".replaceAll("\\[|\\]|\"","").split(",");
merfanzo
  • 33
  • 4