Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a String Array in a JSON object?

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" : ["john", "mat", "jason", "matthew"]
    }

This is the code that I have written :

import org.json.JSONObject;

JSONObject school = new JSONObject();

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

But the last line gives an error. Any way past this?

like image 740
VenkateshShukla Avatar asked Sep 10 '25 08:09

VenkateshShukla


1 Answers

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));
like image 148
bhavindesai Avatar answered Sep 12 '25 21:09

bhavindesai