It might be too easy but I just cannot find a solution to this. How can I directly parse the string
array
out of the JSON
object?
For example,
json = {"names":["John", "Alex", "David"]}
I cannot do json.getJSONArray("names")
since it doesn't return a string
array
.
You can get the data as a json array and the loop through it to create a list
JSONObject jsonObject = new JSONObject("{names:['1','2','3']}");
JSONArray jsonArray = jsonObject.getJSONArray("names");
List<String> names = new ArrayList<String>();
for(int i = 0; i < jsonArray.length(); i++){
names.add(jsonArray.getString(i));
}
System.out.println(names);
You can try this my friend
try
{
JSONObject jsonObj = new JSONObject("Your json string");
JSONArray jsonArray = jsonObj .getJSONArray("names");
for(int i=0;i<jsonArray .length();i++)
{
String name= jsonArray.getString(i);
Log.i("..........",""+name);
// loop and add it to array or arraylist
}
}catch(Exception e)
{
e.printStackTrace();
}
Try this buddy, you will get the result in an array of strings.
String json = "{\"names\":[\"John\", \"Alex\", \"David\"]}";
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("names");
List<String> list = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getString(i));
}
String[] stringArray = list.toArray(new String[list.size()]);
Try this function
public void ParseJsonArray(json){
try {
//if you have 1 column in json array
JSONArray jsonArray = json.getJSONArray("names");
int count = 0;
//if you have more columns
while (count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count);
String s1 = JO.getString("column1");
String s2 = JO.getString("column2");
String s3 = JO.getString("column3");
count++; }``
String StrFinal = jsonArray;
} catch (JSONException e) {
e.printStackTrace(); }
}