Android - 如何解析json对象的意图?

时间:2016-12-29 05:25:53

标签: android json

我想将我的意图添加到json对象,但是如何使用下面的代码

Pojo.java

    //getter and setter on above code
    JSONObject obj = new JSONObject();
    try {
        obj.put("id", id);
        obj.put("nilai", ratingStar);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return obj;
}

Main.java

 for (int i=0;i<size;i++){
   jArray.put(adapter3.getItem(i).getJsonObject());
 }
JSONObject j=new JSONObject();
try {
  j.put("fishing",jArray);
  Log.d("json output : ",j.toString());
} catch (JSONException e) {
  e.printStackTrace();
}

来自Log.d("json output : ",j.toString());的响应是:

{"fishing":[{"id":"1","nilai":1},{"id":"2","nilai":1},{"id":"3","nilai":1},{"id":"4","nilai":1},{"id":"5","nilai":1}]}

但我想将我的意图添加到json对象中,就像这样

{"fishing":[{|"id_dosen":"2","id_matkul":"3"|,"id":"1","nilai":1},{|"id_dosen":"2","id_matkul":"3"|,"id":"2","nilai":1},{|"id_dosen":"2","id_matkul":"3"|,"id":"3","nilai":1},{|"id_dosen":"2","id_matkul":"3"|,"id":"4","nilai":1},{|"id_dosen":"2","id_matkul":"3"|,"id":"5","nilai":1}]}

有人可以帮我如何添加我用|标记的json吗?

注意:我使用|符号只是为了让您轻松阅读第一个json与第二个json的不同

1 个答案:

答案 0 :(得分:0)

您可以像这样在JSON中添加这些字段。

String jsonFishing = "{\"fishing\":[{\"id\":\"1\",\"nilai\":1},{\"id\":\"2\",\"nilai\":1},{\"id\":\"3\",\"nilai\":1},{\"id\":\"4\",\"nilai\":1},{\"id\":\"5\",\"nilai\":1}]}";
try {
  JSONObject rootObj = new JSONObject(jsonFishing);
  JSONArray fishingArr = rootObj.getJSONArray("fishing");
  for (int i = 0; i < fishingArr.length(); i++){
    JSONObject child = fishingArr.getJSONObject(i);
    child.put("id_dosen", 2);
    child.put("id_matkul", 3);
  }
  ...
  yourIntent.putExtra("json", rootObj.toString());
} catch (JSONException e) {
   e.printStackTrace();
}

新获得的JSON看起来像这样。

{"fishing":[{"id":"1","nilai":1,"id_dosen":2,"id_matkul":3},{"id":"2","nilai":1,"id_dosen":2,"id_matkul":3},{"id":"3","nilai":1,"id_dosen":2,"id_matkul":3},{"id":"4","nilai":1,"id_dosen":2,"id_matkul":3},{"id":"5","nilai":1,"id_dosen":2,"id_matkul":3}]}

编辑:在你的代码中,它就像这样

for (int i=0;i<size;i++){
   JSONObject jsonObject = adapter3.getItem(i).getJsonObject();
   jsonObject.put("id_dosen", 2);
   jsonObject.put("id_matkul", 3);
   jArray.put(jsonObject);
}

希望这会有所帮助:)