我从服务器获取数组中的数据。现在我想将收到的数据(用户名)放入字符串数组中。我不知道将数据放入字符串数组。
代码: -
JSONObject jo = new JSONObject(data);
Log.d("response", jo.toString(4));
JSONArray jArray = jo.getJSONArray("driver_details");
for (int i=0; i < jArray.length(); i++)
{
System.out.println("please print my name...for....");
try {
JSONObject jsob = jArray.getJSONObject(i);
// Pulling items from the array
mfname = jsob.getString("first_name");
}
}
答案 0 :(得分:4)
你有几个选择。一个是使用String []或ArrayList();
JSONObject jo = new JSONObject(data);
Log.d("response", jo.toString(4));
JSONArray jArray = jo.getJSONArray("driver_details");
String[] names = new String[jArray.length()];
for (int i=0; i < jArray.length(); i++)
{
System.out.println("please print my name...for....");
try {
JSONObject jsob = jArray.getJSONObject(i);
// Pulling items from the array
mfname = jsob.getString("first_name");
names[i] = mfname;
}
}
您也可以使用ArrayList():
List<String> names= new ArrayList<String>();
....
names.add(mfname);
答案 1 :(得分:3)
尝试以下代码:
对于Arraylist:
JSONObject jo = new JSONObject(data);
JSONArray jArray = jo.getJSONArray("driver_details");
ArrayList<String> users = new ArrayList<String>();
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject jsob = jArray.getJSONObject(i);
String mfname = jsob.getString("first_name");
users.add(mfname);
}
catch (JSONException e) {
e.printStackTrace();
}
}
对于String数组:
JSONObject jo = new JSONObject(data);
JSONArray jArray = jo.getJSONArray("driver_details");
String[] users = new String[jArray.length()];
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject jsob = jArray.getJSONObject(i);
String mfname = jsob.getString("first_name");
users[i] = mfname;
}
catch (JSONException e) {
e.printStackTrace();
}
}
答案 2 :(得分:3)
试试这个..
对于字符串数组
String[] array_items = new String[jArray.length()];
for (int i=0; i < jArray.length(); i++)
{
try{
JSONObject jsob = jArray.getJSONObject(i);
array_items[i] = jsob.getString("first_name");
} catch (JSONException e) {
e.printStackTrace();
}
}
对于 String ArrayList
ArrayList<String> arraylist_items = new ArrayList<String>();
for (int i=0; i < jArray.length(); i++)
{
try{
JSONObject jsob = jArray.getJSONObject(i);
arraylist_items.add(jsob.getString("first_name"));
}catch (JSONException e) {
e.printStackTrace();
}
}