java - JSON解析 - 如何?
问题描述
您好,我得到了 json,我可以回显显示名称计数和垃圾邮件,但我无法打印结果数组。
[“杰克”,“山姆”,“凯利”]
我的 json: {"results":[{"displayName":"Jack","count":"5","results":["jack","sam","kelly"],"spam":"14 "}]}
我的代码:
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
name = jo.getString("displayName");
count = jo.getString("count");
}
name.setText(name);
解决方案
请尝试以下代码,它可能会解决您的问题:
Java 文件:
public class MainActivity extends AppCompatActivity {
TextView txtname,txtcount,txtspam,txtresults;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtname = (TextView)findViewById(R.id.txtname);
txtcount = (TextView)findViewById(R.id.txtcount);
txtspam = (TextView)findViewById(R.id.txtspam);
txtresults = (TextView)findViewById(R.id.txtresults);
String response = "{\"results\":[{\"displayName\":\"Jack\",\"count\":\"5\",\"results\":[\"jack\",\"sam\",\"kelly\"],\"spam\":\"14\"}]}";
String name="",count="",spam="",results="";
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
name = jo.getString("displayName");
count = jo.getString("count");
spam = jo.getString("spam");
JSONArray jsonArray1 = jo.getJSONArray("results");
for(int j=0;j<jsonArray1.length();j++){
results += jsonArray1.get(j)+",";
}
}
txtname.setText(name);
txtcount.setText(count);
txtspam.setText(spam);
txtresults.setText(results);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
XML 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:id="@+id/txtname"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txtcount"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txtresults"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txtspam"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
推荐阅读
- javascript - React Web 扩展错误:拒绝应用内联样式,因为它违反了以下内容安全性
- python - 将csv导入redis Set
- keyboard - 我一直在使用笔记本电脑,但出现了一些键盘问题(与按键有关)
- google-cloud-platform - 在 myaccount.google.com/permissions 撤销权限后如何从“不可用的凭据无法获取元数据”中恢复
- android - 解决 Kotlin 中 BigDecimal 的错误“未解决的参考。由于接收器类型不匹配,以下候选均不适用”
- javascript - 了解 JavaScript 中键的长度
- here-api - HERE Maps Routing API v8:街道属性
- flutter - Flutter中如何设置WidgetsApp的属性pageRouteBuilder
- android-studio - Android studio-无法使用意图启动新活动
- flutter - 如何更改地图
> 到地图 > 在飞镖?