我试图将json内容解析为我的Android应用程序。我使用firebase db来获得结果。
我有什么
private void StartParse() {
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
webserviceUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Repsonse", response.toString());
try {
// Parsing json object response
// response will be a json object
String cover = response.optString("cover").toString();
String ip_address = response.optString("ip_address").toString();
String port = response.optString("port").toString();
String info = response.optString("info").toString();
String uid = response.optString("uid").toString();
Map<String, String> map = new HashMap<String, String>();
map.put(cover, cover.toString());
// and so on..
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Response", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
// hide the progress dialog
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
我需要什么 是我在这里有这个json的回应:
{
"-KFOmfn3XcmM3BsrWYcZ":{
"company":"A17",
"country":"France",
"email":"test12@gmail.com",
"uid":"720363f7-84f1-4a35-9551-9422da991835"
},
"-KTCLolTzHO0KFcuQR3B":{
"company":"B13",
"country":"Sweden",
"email":"test14@gmail.com",
"uid":"7eade882-c182-441e-8793-94c6a1879a52"
},
"-KFcuQR3B1KTCLsa43BK10":{
"company":"C23",
"country":"Denmark",
"email":"France",
"uid":"7eade882-c182-441e-8793-94c6a1879a52"
},
"-CLHOcuQoKFzRTl3BKx0T":{
"company":"4SS",
"country":"Italy",
"email":"test1@gmail.com",
"uid":"7eade882-c182-441e-8793-94c6a1879a52"
}
}
响应是json文件,但我怎样才能获取值?所以我可以只有一个数值的数组。
答案 0 :(得分:3)
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
答案 1 :(得分:0)
没有Json数组,因此您可以逐个解析对象键。像这样的东西
JSONObject jsonObject = new JSONObject(response);
String company = jsonObject.getJSONObject("-KFOmfn3XcmM3BsrWYcZ").getString("company");
String country= jsonObject.getJSONObject("-KFOmfn3XcmM3BsrWYcZ").getString("country");
// email and uid same
String company1 = jsonObject.getJSONObject("-KTCLolTzHO0KFcuQR3B").getString("company");
String country1= jsonObject.getJSONObject("-KTCLolTzHO0KFcuQR3B").getString("country");
......