如何使用Gson序列化android中的对象?

Sur*_*mad 5 java android json jsonserializer gson

我想使用socket从Android客户端向Java服务器发送2个对象(因为我正在开发远程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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

当然我知道上面的方法不会起作用,因为它会给出ClassNotFoundException().所以现在我想知道如何使用Gson库来序列化和反序列化对象.提前致谢.

bur*_*gar 15

gson可以在任何平台上与Java一起使用 - 不仅仅是Android.

使用gson序列化单个对象:

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

使用gson反序列化为单个对象.

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

正如你从例子中看到的那样,gson非常神奇:)它实际上并不神奇 - 你需要确保至少一些东西:

确保您的类具有无args构造函数,以便gson库可以轻松获取实例.

确保属性名称与json中的属性名称匹配,以便gson库可以将json中的字段映射到类中的字段.

另请参阅https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples