Create and read simple JSON_STRING in Android Studio


JSON_STRING strings are similar to Dictionary and List in Python, they can be searched quickly. JSON_STRING can be used to store data for your application.

This post will teach you how to create and read JSON_STRING objects in Android Studio/Eclipse Android apps.

  1. Go ahead and create a simple activity app
  2. Switch to Android View
  3. Create simple JSON_STRING as follows in the MainActivity.Java class
    String JSON_STRING = "{\"DSLR\":{\"Model\":\"Sony Alpha 58\",\"Sensor\":APC}}";

    [Drop the above code at the beginning of the OnCreate method]

  4. Open main_activity.xml [can find under res/layout]
  5. Drag and Drop two TextView control to the Form.
  6. Change the name of the controls in the content_main.xml file as ‘model’ and ‘sensor’ respectively
  7. Now create variable to read a string from JSON and assign the values to controls
String model, sensor;
TextView Model, Sensor;
Model = (TextView) findViewById(R.id.model);
Sensor = (TextView) findViewById(R.id.sensor);
try {
 // get JSONObject from JSON file
 JSONObject obj = new JSONObject(JSON_STRING);
 // fetch JSONObject named employee
 JSONObject dslr = obj.getJSONObject("DSLR");
 // get employee name and salary
 model = dslr.getString("Model");
 sensor = dslr.getString("Sensor");
 // set employee name and salary in TextView's
 Model.setText("Model: "+model);
 Sensor.setText("Sensor: "+sensor);

} catch (JSONException e) {
 e.printStackTrace();
}

Alt+Enter to auto import libraries. Here the JSONObject will help you to fetch ‘DSLR’ String. In our example, we have one only one JSON string so that used two Text views only.

Remember JSON strings are case sensitive.

You can download the source code from GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.