I do not understand why I can not get the key content. Fulfills a catch block. What am I doing wrong?

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { TextView txt1; //{"Sensor":{ "name":"Accelerometer","value":"-0,6 5,3 8,3"},{ "name2":"Orintation","value2":"0,0 0,0 0,0"} } public static final String JSON_STRING = "{\"Sensor\":\n" + "\t{ \"name\":\"Accelerometer\",\n" + "\t \"value\":\"-0,6\t\t5,3\t\t8,3\"\n" + "\t},\n" + "\t{ \n" + "\t\t\"name2\":\"Orintation\",\n" + "\t\t\"value2\":\"0,0\t\t0,0\t\t0,0\"\n" + "\t} \n" + "} "; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txt1= (TextView) findViewById(R.id.txt1); } public void myAction(View view){ myJSONParse(); } private void myJSONParse() { try{ JSONObject jObj=(new JSONObject(JSON_STRING)).getJSONObject("Sensor"); String str=jObj.getString("name"); txt1.setText(str); }catch (Exception e) {e.printStackTrace();} } } 

Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.json.JSONObject.toString ()

How to parse it correctly?

  • one
    and your JSON is not valid ... jsonlint.com check here },{ obviously something is not right. Or is it an array? - pavel
  • it is not an array, I don’t even know where a mistake might be, but what’s wrong with validity? - mtb
  • and it seems to me an array. { "Sensor": [{ "name": "Accelerometer", "value": "-0,6 5,3 8,3" }, { "name2": "Orintation", "value2": "0,0 0,0 0,0" }] } Then you should not write getJSONObject but getJSONArray or something like that - pavel
  • no, I specifically commented on the original line {"Sensor": {"name": "Accelerometer", "value": "- 0.6 5.3 8.3"}, {"name2": "Orintation", "value2" : "0.0 0.0 0.0"}} here without an array! - mtb
  • 2
    I say it again ... This is not valid JSON. Fix it. - pavel

0