How to add a String Array in a JSON object?

后端 未结 5 717
孤城傲影
孤城傲影 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:28

    @bhavindesai's, answer is great answer. Here is another way to solve this issue. You can simply do it using Json Simple library. Here is the gradle

    compile 'com.googlecode.json-simple:json-simple:1.1'
    

    Here is sample code:

    org.json.simple.JSONObject jsonObject=new org.json.simple.JSONObject();
    jsonObject.put("Object","String Object");
    
    ArrayList<String> list = new ArrayList<String>();
                list.add("john");
                list.add("mat");
                list.add("jason");
                list.add("matthew");
    
                jsonObject.put("List",list);
    

    That's it. :)

    0 讨论(0)
  • 2021-01-03 20:31

    As bhavindesai noted,

    ArrayList<String> list = new ArrayList<String>();
    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

     <dependency>
        <groupId>com.googlecode.json-simple</groupId>
        <artifactId>json-simple</artifactId>
        <version>1.1</version>  
    </dependency>
    

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

    0 讨论(0)
  • 2021-01-03 20:39

    You are getting error because of this.

    school.put("name", ["john", "mat", "jason", "matthew"] );
                       ^                                 ^   
    

    Do like this.

    school.put("name", new JSONArray("[\"john\", \"mat\", \"jason\", \"matthew\"]"));
    
    0 讨论(0)
  • 2021-01-03 20:43

    Little improper approach suggested by Tom. Optimised code would be:

    ArrayList<String> list = new ArrayList<String>();
    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));
    
    0 讨论(0)
  • 2021-01-03 20:43

    You're getting an error because your last line is invalid Java.

    school.put("name", new JSONArray("[\"john\", \"mat\", \"jason\", \"matthew\"]"));
    
    0 讨论(0)
提交回复
热议问题