0

I'm receiving a JSONObject like this

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

How do I make it into a String array of

["value1", "value2"]
1
  • key is same for all the values Commented Feb 12, 2014 at 4:23

5 Answers 5

1

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"));

  }
Sign up to request clarification or add additional context in comments.

1 Comment

Can you check the edit please. It's not actually (my mistake) "tag1", "tag2". It's all "tag", "tag".... How do I do it?
1

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());
        }

Comments

0

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");
    }

Comments

0

There is super cool , lib called GSON , which is really helpfull for converting all type of JSON into its object .

Comments

0

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)

2 Comments

I put tag1, tag2 by mistake. Everything comes like "tag"
even better, then use a for each loop and your work is easy :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.