简体   繁体   English

Android序列化 - java反序列化

[英]Android serialization - java deserialization

I'm having some trouble with sending an Object from my Android app to my Java application. 我在将Android应用程序中的Object发送到Java应用程序时遇到了一些麻烦。 I have a serializable class that's exactly the same. 我有一个完全相同的可序列化类。

It works perfectly when I send the object from one java appliction to another one using this code on the receiver side: 当我使用接收器端的代码将对象从一个java应用程序发送到另一个java应用程序时,它工作正常:

@Override
public void run() {
    super.run();
    while(true){
        try{
            if(datagramSocket!=null)datagramSocket.close();
            datagramSocket = new DatagramSocket(PORT);
            buffer = new byte[4096];
            inPacket = new DatagramPacket(buffer, buffer.length);
            datagramSocket.receive(inPacket);

            InetAddress clientAddress = inPacket.getAddress();
            int clientPort = inPacket.getPort();

            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bais));
            Song song = (Song) ois.readObject();
            song.setClientIP(inPacket.getAddress());
            dc.addSong(song);
            datagramSocket.close();

        }catch (IOException e) {
            System.out.println("IOException on receiving song: " + e);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

but when I try to do the same in android (so sending the Song-object from android to java) I'm getting a ClassCastException: 但是当我尝试在android中做同样的事情时(所以将Song-object从android发送到java)我得到了一个ClassCastException:

[Lcom.audiobuddy.serializables.Song; cannot be cast to com.audiobuddy.serializables.Song

First I thought it was because the package name was different, so I changed it on both sides to "com.audiobuddy.serializables". 首先我认为这是因为包名称不同,所以我在两边都改为“com.audiobuddy.serializables”。 But I look at my error, the Android app, changes the package adding "[L" in front and ";" 但我看看我的错误,Android应用程序,更改包“前面加”[L“和”;“ in the back... 在后面...

On both sides the Song-classes have the same serialVersionUID 在两侧,Song-class具有相同的serialVersionUID

The error message says that you try to cast Song[] ( [L(...)Song means an array of Song) to a Song. 错误消息表示您尝试将Song []( [L(...)Song表示乐曲数组)转换为乐曲。

You should probably change your ois.readObject(); 你应该改变你的ois.readObject(); -line with something like this: -line与这样的事情:

Song[] songs = (Song[]) ois.readObject();
Song song = songs[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM