Rohodude
Rohodude

Reputation: 495

Cannot parse JSON: No JsonObject

I have encountered a problem in my Android application. The problem is that the I cannot parse some JSON code because it has no JsonObject. I'm pretty new to programming, and thus have no experience with JSON. Forgive me if this is a newb question. Here is my JSON code:

{
"item_id": "51c3d78797c3e6d8d3b546cf",
"item_name": "Cola, Cherry",
"brand_id": "51db3801176fe9790a89ae0b",
"brand_name": "Coke",
"item_description": "Cherry",
"updated_at": "2013-07-09T00:00:46.000Z",
"nf_ingredient_statement": "Carbonated Water, High Fructose Corn Syrup and/or Sucrose, Caramel Color, Phosphoric Acid, Natural Flavors, Caffeine.",
"nf_calories": 100,
"nf_calories_from_fat": 0,
"nf_total_fat": 0,
"nf_saturated_fat": null,
"nf_cholesterol": null,
"nf_sodium": 25,
"nf_total_carbohydrate": 28,
"nf_dietary_fiber": null,
"nf_sugars": 28,
"nf_protein": 0,
"nf_vitamin_a_dv": 0,
"nf_vitamin_c_dv": 0,
"nf_calcium_dv": 0,
"nf_iron_dv": 0,
"nf_servings_per_container": 6,
"nf_serving_size_qty": 8,
"nf_serving_size_unit": "fl oz",
}

Here's my code in my Android app.

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    EditText one = (EditText) findViewById(R.id.editText1);
    setContentView(R.layout.dbfiller);
    Intent intent = getIntent();
    final String message = intent.getStringExtra("bnum");

    DefaultHttpClient   httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("https://api.nutritionix.com/v1_1/item?upc="+message
            +"&appId=926eed28&appKey=d1366b0005a0d8f6898ff3df44b52867");
    // Depends on your web service
    httppost.setHeader("Content-type", "application/json");

    InputStream inputStream = null;
    String result = null;
    try {
        HttpResponse response = httpclient.execute(httppost);           
        HttpEntity entity = response.getEntity();

        inputStream = entity.getContent();
        // json is UTF-8 by default
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        result = sb.toString();
        JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("");
        String test = (String) json2.get("nf_ingredient_statement");
        one.setText(test);
    } catch (Exception e) { 
        e.printStackTrace();        
    }
    finally {
        try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
    }
}

I think the problem is here:

            JSONObject json= (JSONObject) new JSONTokener(result).nextValue();
        JSONObject json2 = json.getJSONObject("");
        String test = (String) json2.get("nf_ingredient_statement");
        one.setText(test);

But I don't know what I did wrong. I've been banging my head on the wall for a while. Here's my Logcat:

11-29 12:36:13.636: W/System.err(25748): org.json.JSONException: No value for 
11-29 12:36:13.636: W/System.err(25748):    at org.json.JSONObject.get(JSONObject.java:355)
11-29 12:36:13.636: W/System.err(25748):    at org.json.JSONObject.getJSONObject(JSONObject.java:574)
11-29 12:36:13.636: W/System.err(25748):    at com.example.foodsaver2.DatabaseFiller.onCreate(DatabaseFiller.java:57)
11-29 12:36:13.636: W/System.err(25748):    at android.app.Activity.performCreate(Activity.java:5243)
11-29 12:36:13.636: W/System.err(25748):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-29 12:36:13.636: W/System.err(25748):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
11-29 12:36:13.636: W/System.err(25748):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
11-29 12:36:13.636: W/System.err(25748):    at android.app.ActivityThread.access$700(ActivityThread.java:135)
11-29 12:36:13.636: W/System.err(25748):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
11-29 12:36:13.636: W/System.err(25748):    at android.os.Handler.dispatchMessage(Handler.java:102)
11-29 12:36:13.636: W/System.err(25748):    at android.os.Looper.loop(Looper.java:137)
11-29 12:36:13.636: W/System.err(25748):    at android.app.ActivityThread.main(ActivityThread.java:4998)
11-29 12:36:13.636: W/System.err(25748):    at java.lang.reflect.Method.invokeNative(Native     Method)
11-29 12:36:13.636: W/System.err(25748):    at java.lang.reflect.Method.invoke(Method.java:515)
11-29 12:36:13.636: W/System.err(25748):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-29 12:36:13.636: W/System.err(25748):    at  com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-29 12:36:13.636: W/System.err(25748):    at dalvik.system.NativeStart.main(Native Method)

The app doesn't crash because the json parser is located inside a try-catch method. What's wrong here? I've checked Google and SO, but I can't seem to find the solution. Any help regarding this problem is greatly appreciated.

Upvotes: 0

Views: 1073

Answers (3)

Tarek Kanon
Tarek Kanon

Reputation: 98

its a little stupid but give it a shot :)

    String finalResult;
    finalResult= result.substring(0, result.length() -2) + "}";
    Log.i("finalResult", finalResult);

Upvotes: 0

mttdbrd
mttdbrd

Reputation: 1831

There's an error in your JSON. Remove the comma at the end of this line and try again:

"nf_serving_size_unit": "fl oz",
}

You can always check to see if your JSON is valid using the JSON validator at jsonlint.com.

Upvotes: 0

Eric Wich
Eric Wich

Reputation: 1544

Your JSON string has a trailing comma at the end. Chop that off and it will likely fix your problem, as the code looks fine.

Upvotes: 2

Related Questions