2

I need to convert String in Json format to a List object and I am using below program to do it.

public class JsonStringToListConversion {

    public static void main(String[] args) {
        String userProfile = "{\"name\":\"Arun\", Skills:[\"Java\",\"Spring\",\"hibernate\"]}";
        JSONObject userProfileJO = (JSONObject)JSONSerializer.toJSON(userProfile);
        List<String> skills = new ArrayList<String>();
        skills = (List<String>)userProfileJO.getJSONArray("Skills");
        System.out.println(skills);
    }
}

I am using Java 1.6 and JSON-lib 2.4

Please help me to know whether this is the correct way to do this?

Particularly I am typecasting JSONArray to List and it is working whether it is correct?

victor
  • 153
  • 2
  • 14
  • I am surprised that how casting is working?- Actually `JSONArray` needs to iterate and fill the list. [Ex](http://stackoverflow.com/questions/3395729/convert-json-array-to-normal-java-array) – Subhrajyoti Majumder Nov 22 '15 at 18:22
  • 1
    Yes correct Subhrajyoti Majumder that is what my doubt also. – victor Nov 22 '15 at 18:31

3 Answers3

2

You can use this block of code to convert JSONArray to the arraylist object.

JSONArray jsonArray=new JSONArray();
arrayList=new ArrayList();
n=jsonArray.length();
for (int i=0;i<n;i++)
     arrayList.add(jsonArray.get(i));

Happy coding!!

Arpit Agrawal
  • 321
  • 1
  • 2
  • 14
0

Internally this JsonArray implements list interface so type casting to List is perfectly fine. Moreover iterating each and every element will access list one by one which will be overhead(Performance impact).

If you need alternate way you can use toCollection static method from the same JsonArray class

Thilak
  • 367
  • 2
  • 12
0

In Java 8+, the solution can be implemented in a single line.

List<String> elementsList = myJsonArray.toList()
    .stream().map(x -> Objects.toString(x))
    .collect(Collectors.toList());

If you want a different variable instead of String, you can change the list Vector and the appropriate conversion function (Objects.toString(object)).

Caleb Hillary
  • 525
  • 6
  • 10