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?

2
  • I am surprised that how casting is working?- Actually JSONArray needs to iterate and fill the list. Ex Commented Nov 22, 2015 at 18:22
  • 1
    Yes correct Subhrajyoti Majumder that is what my doubt also. Commented Nov 22, 2015 at 18:31

3 Answers 3

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!!

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

Comments

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

Comments

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

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.