[英]Convert JSONObject into String array
I'm receiving a JSONObject like this 我正在收到像这样的JSONObject
{"tag":"value1", "tag":"value2", .............}
How do I make it into a String array of 我如何将它变成一个String数组
["value1", "value2"]
Create the Arraylist and get the string from the jsonobject and stored it in the arraylist. 创建Arraylist并从jsonobject获取字符串并将其存储在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, 如果标签将是tag1,tag2等等......你可以使用for循环,
string[i] = jsonObj.getString("tag"+i);
Or you can make a model class with datatype of String or ArrayList tag , eg. 或者,您可以创建一个数据类型为String或ArrayList标记的模型类,例如。
class ModelClass{
ArrayList<String> tag;
//getter setter here
}
And with that use Gson for JSON parsing and mapping the data, 并使用Gson进行JSON解析和映射数据,
Gson gson = new Gson();
modelClass= gson.fromJson(yourJson,ModelClass.class);
And your work is done. 你的工作已经完成。 You have each value in the ArrayList tag.
您拥有ArrayList标记中的每个值。
This is more useful for parsing and mapping long and-or complex json strings. 这对于解析和映射长和复杂的json字符串更有用。
https://code.google.com/p/google-gson/ https://code.google.com/p/google-gson/
For Naming discrepancies(according to the variables in webservice), can use annotations like @SerializedName. 对于命名差异(根据webservice中的变量),可以使用@SerializedName等注释。 (So no need to use Serializable)
(所以不需要使用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转换为其对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.