这是我的JSON文件:
{
"server_response": [{
"bmw": "",
"mercedes": "",
"honda": "civic",
"toyota": "corolla",
"gmc": "",
"chevy": ""
}]
}
这是我的Android代码:
try {
JSONObject jsonResponse = new JSONObject(JSON_STRING);
JSONArray jsonMainNode = jsonResponse.optJSONArray("server_response");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
//this is the problem here. How can I get JSON that has a result like Honda and Toyota?
{variable name} = jsonChildNode.optString("{problem is here}");
CarsModel carsModel new CarsModel( {variable name} {variable name} );
}
} catch (JSONException e) {
e.printStackTrace();
}
问题出在Android代码中,如您所见。我希望它只能获得非空的JSON,例如本田和丰田。
如何在这种情况下替换{变量名},本田然后用json结果替换{问题在这里}并不是空白的?
我还想将{变量名}添加到CarsModel carsModel new CarsModel( {variable name} {variable name} );
。
答案 0 :(得分:0)
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
// Get the keys in the JSON object
Iterator<?> keys = jsonChildNode.keys();
while (keys.hasNext()) {
// Get the key
String key = (String)keys.next();
String objValue = jsonChildNode.getString(key);
// check if empty
if (!objValue.isEmpty()) {
CarsModel carsModel new CarsModel(objValue);
}
}
}
答案 1 :(得分:0)
这是你需要做的。您想要的数据是jsonArray
中的json对象JSONObject jsonResponse = new JSONObject(JSON_STRING);
JSONArray jsonMainNode = jsonResponse.optJSONArray("server_response");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
variableX = jsonChildNode.getString("toyota");
variableY = jsonChildNode.getString("honda");
variableZ = jsonChildNode.getString("xyz");
// CarsModel thing using var x, y, z...
}