android - Android中没有数组名称或节点的JSON解析
问题描述
我有一个没有数组名称的 JSOn 数组,我很困惑如何解析它以及如何制作 JSONObject 或 JSONArray。如果可能的话,请描述一下。
我的 JSON 数组列表是:
[{
name:"Product_fill",
image:"https://something.com/product1.jpg",
title:"Laptop 1"
},
{
name:"Product_fill2",
image:"https://something.com/product2.jpg",
title:"Laptop 2"
},
我的代码是:
RequestQueue queue= Volley.newRequestQueue(this);
String Url="http://msomething.com/list.php";
StringRequest request=new StringRequest(Request.Method.GET, Url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//weatherData.setText("Response is :- ");
parseData(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textView.setText("Data Not Received");
}
});
queue.add(request);
super.onStart();
}
private void parseData(String response) {
try {
// Create JSOn Object
JSONObject jsonObject=new JSONObject(response);
JSONObject main=jsonObject.getJSONObject("array");
JSONArray jsonArray=jsonObject.getJSONArray("0");
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1=jsonArray.getJSONObject(i);
textView.setText(jsonObject1.getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
解决方案
您可以将响应字符串直接传递给 JSONArray 构造函数,然后使用循环解析数组
JSONArray jsonArray = new JSONArray(response);
提示:我会搜索如何使用其他 json 库,如 Gson 或 Jackson,因为 Android 内置解析器不好。
推荐阅读
- r - 使用两列删除另一个数据框中存在的行
- react-native - React Native SVG Mask子不转换
- c - @zero_extendqisi2 的含义
- spring-boot - spring-data-jdbc - 为什么我得到 DbActionExecutionException 而不是 DuplicateKeyException
- linux - 字符串的正确转义策略
- html - 具有全屏高度和滚动内容面板的 TailwindCss 布局
- amazon-web-services - 如何访问 Go AWS lambda 函数中的参数
- php - Symfony Guard 或 Userprovider - 用户名始终为空
- c++ - 我想用阶乘将我的代码从 python 移植到 c++
- html - 如何使嵌入谷歌表单响应?