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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28391982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:31:57  来源:igfitidea点击:

How to use Gson to serialize objects in android?

javaandroidjsongsonjsonserializer

提问by Suroor Ahmmad

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

我想使用套接字从 Android 客户端向 Java 服务器发送 2 个对象(因为我正在开发远程 PC)。

AndroidClient.java

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

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.

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

回答by burntsugar

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

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

Using gson to serialize a single object:

使用 gson 序列化单个对象:

    // 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.

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

    // 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:

从示例中可以看出,gson 非常神奇:) 它实际上并不神奇——您至少需要确保以下几点:

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

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

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.

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

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

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