0

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:191is 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 ?

4
  • I think the problem is something else. I tried JSONObject jsonObject = new JSONObject(yourJson) and it threw JsonToken.syntaxError. After digging a while i found out that it is not able to parse "\\/" in your image_url field. Might be that is the reason you are getting NullPointerException. Commented Mar 22, 2016 at 16:30
  • Gotta! There is something wrong with your json. .... "image_url":"\/append_img\/telinga.png [ ” ] }, { [ “ ] level":"lv1", Characters in [ ] should be quotes (") but are something different. If you change them to quotes, they will be parsed easily and null pointer will not be thrown. Commented Mar 22, 2016 at 16:46
  • i tried to only getting name_eng but still have same problem. i think its not about son structure. Commented Mar 22, 2016 at 16:53
  • I have tried the solution i posted, i guess that will work for you too. :) Let me know if I could be of anymore help. Commented Mar 22, 2016 at 17:04

3 Answers 3

3

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

filterArr.put(filterJson) aways be nullException
use AssertNotNull(filterArr) instead of assert filterArr != null; and try again.
what is at startgameActivity.java:191?
filterArr.put(filterJson);
1

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.

Comments

0

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();
                }

2 Comments

i had try this but not working, filterArr.put(filterJson) aways be nullException
And when you say it's "not working" what is not working?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.