How to add a String Array in a JSON object?

后端 未结 5 736
孤城傲影
孤城傲影 2021-01-03 19:49

I am trying to create this JSON object on android. I am stuck on how to add a string array in the object.

A = {
    \"class\" : \"4\" ,
    \"name\" : [\"joh         


        
5条回答
  •  失恋的感觉
    2021-01-03 20:31

    As bhavindesai noted,

    ArrayList list = new ArrayList();
    list.add("john");
    list.add("mat");
    list.add("jason");
    list.add("matthew");
    
    JSONObject school = new JSONObject();
    
    school.put("class","4");
    school.put("name", new JSONArray(list));
    

    is a much better and cleaner approach.

    To import the right package you should write:

    import org.json.simple.JSONArray;
    

    on top of java class.

    And if you are using Maven, add

     
        com.googlecode.json-simple
        json-simple
        1.1  
    
    

    to pom.xml. Then, Download sources & dependencies and Reimport. I answered though I used commenting, since commenting screwed up the code indentation.

提交回复
热议问题