【发布时间】:2023-04-09 16:30:01
【问题描述】:
从一个 Rest API,我得到以下格式的 json 数据:
[
{
"id": "1",
"item": "tea",
"price": "7.5",
"image": "http:\/\/192.168.1.3\/CI\/images\/tea.jpg",
"veg": "0",
"category": "drinks"
},
{
"id": "2",
"item": "coffee",
"price": "10",
"image": "http:\/\/192.168.1.3\/CI\/images\/coffee.jpg",
"veg": "0",
"category": "drinks"
}
]
从 API 我得到 Json 作为一个字符串,它在 url 的正斜杠前面包含反斜杠,这是根据 json 编码规范。而且我能够正确地从 json_decode 并从 php 获取 url。在 android 中,我将 json 字符串存储在名为“menu_json”的变量中。
然后我尝试使用以下代码解析并从中获取图像 url:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
try{
JSONObject menuApiObj = new JSONObject(menu_json);
JSONArray menuObj = menuApiObj.getJSONArray("menu");
for (int i = 0; i < menuObj.length(); i++){
JSONObject row = menuObj.getJSONObject(i);
rowString = row.getString("image");
imageUrl = row.toString();
Log.e("rowString", rowString);
Log.e("imageUrl", imageUrl);
}
我得到的输出是:
{
"id": "1",
"item": "tea",
"price": "7.5",
"image": "tea.jpg",
"veg": "0",
"category": "drinks"
}
图像字段应该是:
http://192.168.1.3/CI/images/tea.jpg
但我得到的只是:
tea.jpg
当 json_decode PHP 中的 API 响应时,我得到正确解码的 url。但在 Android 中,我没有在图像字段中获得正确解码的 url。
请帮忙!
这是完整的 API 响应:
{"menu":[{"id":"1","item":"tea","price":"7.5","image":"tea.jpg","veg":"0","category":"drinks"},{"id":"2","item":"cofee","price":"10","image":"coffee.jpg","veg":"0","category":"drinks"},{"id":"3","item":"crispy chicken","price":"160","image":"crispy-chicken.jpg","veg":"0","category":"curries"}],"cat_wise":[{"category":"drinks","items":[{"id":"1","item":"tea","price":"7.5","image":"http:\/\/192.168.1.3\/CI\/images\/tea.jpg","veg":"0","category":"drinks"},{"id":"2","item":"cofee","price":"10","image":"http:\/\/192.168.1.3\/CI\/images\/coffee.jpg","veg":"0","category":"drinks"}]},{"category":"curries","items":[{"id":"3","item":"crispy chicken","price":"160","image":"http:\/\/192.168.1.3\/CI\/images\/crispy-chicken.jpg","veg":"0","category":"curries"}]},{"category":"main","items":[]}]}
【问题讨论】:
-
显示完整的 JSON 数据。
menuApiObj.getJSONArray("menu")是什么意思?给定的 JSON 数据中没有这样的数组,