简体   繁体   中英

How can create JSON Object and put in JSON Array by for loop in android?

I have i JSON Object instead an JSON Array, i want to get the value and create new JSON Object and put into JSON Array again.

Here my JSONObject called response

{"data":
 [{
    "level":"lv1",
    "name_indo":"Telinga",
    "name_eng":"Ear",
    "detail_indo":"Telinga adalah alat indra yang memiliki fungsi untuk mendengar suara yang ada di sekitar kita.\r\n",
    "detail_eng":"The ear is the sensory apparatus that has a function to hear the sounds that are around us .\r\n",
    "image_url":"\/append_img\/telinga.png”},
{
    “level":"lv1",
    "name_indo":"Gigi",
    "name_eng":"Tooth",
    "detail_indo":"Gigi adalah alat yang digunakan untuk mengolah makanan saat kita makan.\r\n",
    "detail_eng":"Gigi is a tool used to process food when we eat.\r\n",
    "image_url":"\/append_img\/gigi.png"}]
}

Here my Code for make a new JSON Array only containing name_eng value and image_url value :

                    try {
                    JSONArray resultArr = response.getJSONArray("data");

                    JSONObject filterJson = null;
                    JSONArray filterArr = null;
                    for (int i = 0; i < resultArr.length(); i++) {
                        Log.v(TAG, "run for");
                        JSONObject finalObj = (JSONObject) resultArr.get(i);
                        String name_eng = finalObj.getString("name-eng");
                        filterJson = new JSONObject();
                        filterJson.put("name_eng", name_eng);

                        filterArr = new JSONArray();
                        filterArr.put(filterJson);
                    }
                    JSONObject fixedJSON = new JSONObject();
                    assert filterArr != null;
                    fixedJSON.put("data", filterArr.toString());
                    Log.v(TAG, "filterarray : "+fixedJSON);
                    } catch (JSONException e) {
                     e.printStackTrace();
                    }

This is my LogCat Error :

03-22 23:50:42.864 10867-10867/tk.partofbodyapp.partofbodyapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: tk.partofbodyapp.partofbodyapp, PID: 10867
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONArray.put(java.lang.Object)' on a null object reference
                                                                                at tk.partofbodyapp.partofbodyapp.startgameActivity$startJson.onPostExecute(startgameActivity.java:191)
                                                                                at tk.partofbodyapp.partofbodyapp.startgameActivity$startJson.onPostExecute(startgameActivity.java:88)
                                                                                at android.os.AsyncTask.finish(AsyncTask.java:636)
                                                                                at android.os.AsyncTask.access$500(AsyncTask.java:177)
                                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

The error startgameActivity.java:191 is filterArr.put(filterJson);

And I want make an JSON again lie this :

{"data":
 [{
    "name_eng":"Ear",
    "image_url":"\/append_img\/telinga.png”},
{
    "name_eng":"Tooth",
    "image_url":"\/append_img\/gigi.png"}]
}

Any idea ?

try this

try {
    JSONArray resultArr = response.getJSONArray("data");
    JSONArray filterArr = new JSONArray();
    for (int i = 0; i < resultArr.length(); i++) {
        Log.v(TAG, "run for");
        JSONObject filterJson = new JSONObject();
        JSONObject finalObj = (JSONObject) resultArr.get(i);
        String name_eng = finalObj.getString("name-eng");
        String image_url = finalObj.getString("image_url");
        filterJson.put("name_eng", name_eng);
        filterJson.put("image_url", image_url);
        filterArr.put(filterJson);
    }
    JSONObject fixedJSON = new JSONObject();
    assert filterArr != null;
    fixedJSON.put("data", filterArr);
    Log.v(TAG, "filterarray : "+fixedJSON);
} catch (JSONException e) {
    e.printStackTrace();
}

Well, don't you worry, here is an easy way to do it just in 5 simple steps.

1 : Create a model POJO - Containing only the fields that are required in you output json.

public class Model2 {

   String name_eng;
   String image_url;

   //Create Getters and Setters

}

2 : Create Json object from the json - input is your json string

JSONObject jsonObject = new JSONObject(json);

3: Get the JSONArray and convert it to list of objects

Type listType = new TypeToken<ArrayList<Model2>>() { }.getType();
List<Model2> outputList = new Gson().fromJson(jsonObject.getJSONArray("data").toString(), listType);

(Used Gson to convert json to Object. Must be some good way to do with JSON library also)

4 : Create new JSONObject - to send the response

 JSONObject newJsonObject = new JSONObject();

5: add the outputList to newJsonObject

newJsonObject.put("data", outputList);

PS : Your json is not serializable, until you do changes i said to you in comment.

The problem is that you're creating a new JSONArray every pass through the loop. Also make sure you're getting all of the info you want to filter each loop iteration.

                try {
                JSONArray resultArr = response.getJSONArray("data");

                JSONObject filterJson = null;
                JSONArray filterArr = new JSONArray();
                for (int i = 0; i < resultArr.length(); i++) {
                    Log.v(TAG, "run for");
                    JSONObject finalObj = (JSONObject) resultArr.get(i);
                    String name_eng = finalObj.getString("name_eng");
                    String image_url = finalObj.getString("image_url");

                    filterJson = new JSONObject();
                    filterJson.put("name_eng", name_eng);
                    filterJson.put("image_url", image_url);

                    filterArr.put(filterJson);
                }
                JSONObject fixedJSON = new JSONObject();
                assert filterArr != null;
                fixedJSON.put("data", filterArr.toString());
                Log.v(TAG, "filterarray : "+fixedJSON);
                } catch (JSONException e) {
                 e.printStackTrace();
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM