如何获取json数组的每个值?我使用textview中的append来读取所有值。但我想要的是如何获取每个值来设置每个textview。
public void JSONparse() {
String url = "https://api.myjson.com/bins/mat2d";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override public void onResponse(JSONObject response) {
try {
JSONArray JA = response.getJSONArray("products");
for (int i=0; i<JA.length();i++){
Log.d("Result",JA.getString(i));
t1.append(JA.getString(i)+"\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rq.add(request);
}
我的Logcat
02-28 09:29:50.132 3101-3101/com.example.coorsdev.testing D/Result: Alfonso_Brandy 1000mL Imported Brandy
02-28 09:29:50.132 3101-3101/com.example.coorsdev.testing D/Result: Gran_Matador 350mL Regular Brandy
答案 0 :(得分:0)
使用Stringutils.split()
按白度分割字符串。例如,StringUtils.split("Hello World")
会返回"Hello"
和"World"
;
或者您可以使用whitespace regex
:
String str = "Hello I'm your String";
String[] splited = str.trim().split("\\s+"); //use trim to avoid empty strings
结果将是:
splited [0] == "Hello";
splited [1] == "I'm";
splited [2] == "Your";
splited [3] == "String";
public void JSONparse() {
String url = "https://api.myjson.com/bins/mat2d";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override public void onResponse(JSONObject response) {
try {
JSONArray JA = response.getJSONArray("products");
for (int i=0; i<JA.length();i++){
StringUtils.split(JA.getString(i))
// or
String[] splited = JA.getString(i).trim().split("\\s+");
Log.d("Result",JA.getString(i));
t1.append(JA.getString(i)+"\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rq.add(request);
}