![](/img/trans.png)
[英]How to find out json response is an empty JSON object in android?
[英]how do I find out a JSON Object return JSON Array or string in android
我有一个类似以下的json。 如何在android中找到JSON对象返回JSON数组或字符串。
{
"green_spots": [
......
],
"yellow_spots": "No yellow spot available",
"red_spots": "No red spot available"
}
当值存在时,JSON对象重新生成数组,否则返回一个字符串,如“没有绿色/红色/黄色可用点”。 我按照以下方式完成了。 但还有其他办法吗? 因为警报字符串被更改,If将无法正常工作。
JSONObject obj = new JSONObject(response);
String green = obj.getString("green_spots");
// Green spots
if ("No green spot available".equalsIgnoreCase(green)) {
Log.v("search by hour", "No green spot available");
} else {
JSONArray greenArray = obj.getJSONArray("green_spots");
....
}
Object object = jsonObject.get("key");
if (object instanceof JSONObject) {
// It is json object
} else if (object instanceof JSONArray) {
// It is Json Array
} else {
// It is a String
}
你可以使用instanceof
而不是getString只做obj.get将返回一个Object,检查对象是否为instanceof String或JSONArray
编辑:
这里有一些示例代码:
Object itineraries = planObject.get("itineraries");
if (itineraries instanceof JSONObject) {
JSONObject itinerary = (JSONObject) itineraries;
// right now, itinerary is your single item
}
else {
JSONArray array = (JSONArray) itineraries;
// do whatever you want with the array of itineraries
}
JSONObject obj = new JSONObject(response);
JSONArray greenArray = obj.getJSONArray("green_spots");
if(greenArray!=null){
do your work with greenArray here
}else{
Log.v("search by hour", "No green spot available");
}
简单只需打印Log.e(“TAG”,“See >>”JsonObject.toString)之类的对象; 如果响应在{}块中,则它是对象,如果它在[]其数组中
警告:此信息可能是多余的,但它可能被证明是解决此问题的另一种方法。
您可以使用Jackson Object Mapper将JSON文件转换为HashMap。
public static HashMap<String, Object> jsonToHashMap(
String jsonString) {
Map<String, Object> map = new HashMap<String, Object>();
ObjectMapper mapper = new ObjectMapper();
try {
// convert JSON string to Map
map = mapper.readValue(jsonString,
new TypeReference<HashMap<String, Object>>() {
});
} catch (Exception e) {
e.printStackTrace();
}
return (HashMap<String, Object>) map;
}
这会自动创建适当对象的HashMap。 然后,您可以使用instanceof或找出另一种方式来适当/需要使用这些对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.