Tuesday, July 17, 2012

Simple JSON Example

After Adding GSON to your project, you can use it as follows.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
       />
</LinearLayout>

JSON_structure.java 
package beanmatrix.JSON;
public class JSON_structure {

              public String name;
              public String date;
              public String[] message;
}


JSONexampleActivity.java
package beanmatrix.JSON;
import android.app.Activity;
import com.google.gson.Gson;
import android.os.Bundle;
import android.widget.TextView;


public class JSONexampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
              /* Inflate TextView from the layout */
              TextView text = new TextView (this);
              /* JSON data considered as an example. Generally this data is obtained
              from a web service.*/
              String json = " {" + " \"name\": \"BeanMatrix\", " + " \"message\": [\"My JSON Example\",\"Using GSON For Parsing\"]," + " \"date\": \"17-7-2012\" "+ "}";
              Gson gson = new Gson();
              JSON_structure obj= gson.fromJson(json, JSON_structure.class);
              text.setText("Name: "+ obj.name +"\n\n");
              setContentView(text);
              text.append("Date: "+ obj.date +"\n\n");
              for(int i=0;i<obj.message.length;i++)
              {
                     text.append("Message: "+ obj.message[i] +"\n\n");
              }
              }
              catch(Exception ex){ex.printStackTrace();}
              }
}




2 comments:

  1. Gson is a Java library that can be used to convert Java Objects into their JSON representation. It is provided by google. It can also be used to convert a JSON string to an equivalent Java object.

    To use Gson, you need to download it and import it as an External jar file. That I’ve already done.

    Then you need to import it using,
    import com.google.gson.Gson;

    And then I’ve created an object of Gson,
    Gson gson = new Gson();
    Then you can use it as shown in an Example.

    ReplyDelete