Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Gson to serialize objects in android?

I want to send 2 objects to Java server from Android client using socket (as I am developing a Remote PC).

AndroidClient.java

    public class MainActivity extends Activity{
        Socket client;
        ObjectOutputStream oos;
        OutputStream os;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
                    SendObj so=new SendObj();
                    so.execute();
        }

        class SendObj extends AsyncTask<Void, Void, Void>{
            @Override
            protected Void doInBackground(Void... arg0) {
                    try {
                        client=new Socket("192.168.237.1",6566);
                        os=client.getOutputStream();
                        oos=new ObjectOutputStream(os);
                        Serializer ma=new Serializer(2, "Helllo");
                        Log.i("Serial",""+ma.name);
                        oos.writeObject(ma);
                        oos.writeObject(new String("Another Object from Client"));
                        oos.close();
                        os.close();
                        client.close();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

    }

    @SuppressWarnings("serial")
    class Serializer  implements Serializable {
        int num;
        String name;
        public Serializer(int num,String name){
            this.name=name;
            this.num=num;
        }
    }

JavaServer.java

public class ObjectReceiver {
        static ServerSocket server;
        static Socket client;
        static ObjectInputStream ois;
        static InputStream is;

        public static void main(String[] arg) throws IOException, ClassNotFoundException{
            server=new ServerSocket(6566);
            System.out.println("Wait");
            while(true){
                client=server.accept();
                System.out.println("Connected");
                is=client.getInputStream();
                ois=new ObjectInputStream(is);
                try {
                    ObjectSerail or = (ObjectSerail) ois.readObject();
                    if(or!=null){
                        System.out.println("Done");
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }

        @SuppressWarnings("serial")
        class ObjectSerail implements Serializable{
             int num;
             String name;
            public ObjectSerail(int num,String name){
                this.name=name;
                this.num=num;
            }
        }
    }

Of course I know the above method won't work because it will gives ClassNotFoundException(). So now I want to know how can I use Gson library to serialize and deserialize the objects. Thanks in advance.

like image 967
Suroor Ahmmad Avatar asked Feb 08 '15 08:02

Suroor Ahmmad


People also ask

How do you serialize an object using GSON?

Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object. Program output.

What is the use of GSON in Android?

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

What does GSON toJson do?

Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.

What is the difference between GSON and Jackson?

If you're concerned about parsing speed for your JSON library, choose Jackson for big files, GSON for small files, and JSON. simple for handling both.


1 Answers

gson can be used with Java on any platform – not only Android.

Using gson to serialize a single object:

    // Serialize a single object.    
    public String serializeToJson(MyClass myClass) {
        Gson gson = new Gson();
        String j = gson.toJson(myClass);
        return j;
    }

Using gson to deserialize to a single object.

    // Deserialize to single object.
    public MyClass deserializeFromJson(String jsonString) {
        Gson gson = new Gson();
        MyClass myClass = gson.fromJson(jsonString, MyClass.class);
        return myClass;
    }

As you can see from the examples, gson is quite magical :) It is not actually magical - you need to ensure at least a couple of things:

Ensure that your class has a no args constructor so that the gson library can easily get an instance.

Ensure that the attribute names match those in the json so that the gson library can map fields from the json to the fields in your class.

Also see https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples

like image 177
burntsugar Avatar answered Sep 21 '22 23:09

burntsugar