简体   繁体   中英

Convert JSONObject into String array

I'm receiving a JSONObject like this

{"tag":"value1", "tag":"value2", .............}

How do I make it into a String array of

["value1", "value2"]

Create the Arraylist and get the string from the jsonobject and stored it in the arraylist.

Do like this

ArrayList tagarray=new ArrayList();
JSONObject jo=new JSONObject(jsonstring);
for(int i=0;i<jo.length();i++){
tagarray.add(jo.getString("tag"));

  }

Try this way

JSONObject obj = new JSONObject("");
        Iterator<String> itr = obj.keys();
        int i=0;
        String[] values = new String[obj.length()];
        while(itr.hasNext()){
            values[i++] = obj.getString((String)itr.next());
        }

If tags are going to be tag1, tag2 and so on...you can use a for loop,

string[i] = jsonObj.getString("tag"+i);  

Or you can make a model class with datatype of String or ArrayList tag , eg.

class ModelClass{

ArrayList<String> tag; 

//getter setter here
}

And with that use Gson for JSON parsing and mapping the data,

Gson gson = new Gson();

modelClass= gson.fromJson(yourJson,ModelClass.class);

And your work is done. You have each value in the ArrayList tag.

This is more useful for parsing and mapping long and-or complex json strings.

https://code.google.com/p/google-gson/

For Naming discrepancies(according to the variables in webservice), can use annotations like @SerializedName. (So no need to use Serializable)

Use following code.

ArrayList array=new ArrayList();
JSONObject jo=new JSONObject(jsonstring);
for(int i=0;i<jo.length();i++){
  array.add(jo.getString("tag"));
}
String[] Arr = new String[array.size()];
    Arr = array.toArray(Arr);

Or you have another option.

 JSONObject jo=new JSONObject(jsonstring);
    String[] array = new String[jo.length()];
    for(int i=0;i<jo.length();i++){
      array[i] = jo.getString("tag");
    }

有一个名为GSON的超酷lib,它非常有助于将所有类型的JSON转换为其对象。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM