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?
},{obviously something is not right. Or is it an array? - pavel{ "Sensor": [{ "name": "Accelerometer", "value": "-0,6 5,3 8,3" }, { "name2": "Orintation", "value2": "0,0 0,0 0,0" }] }Then you should not writegetJSONObjectbutgetJSONArrayor something like that - pavel