Unserialize in Java a serialized php object

2020-01-26 10:31发布

Does anyone know if it is possible, actually if it has been done, to serialize an object in php and unserialize it in Java (java-php communication). Maybe an adapter will be needed.

What do you think?

Thanks

15条回答
狗以群分
2楼-- · 2020-01-26 11:00

Another Java project to work with the PHP serialization format is Pherialize.

Let's say you are serializing an array like this:

array(3) {
  [0]=>
  string(8) "A string"
  [1]=>
  int(12345)
  [2]=>
  bool(true)
}

Then you can unserialize it in Java with Pherialize like this:

MixedArray list = Pherialize.unserialize(data).toArray();
System.out.println("Item 1: " + list.getString(0));
System.out.println("Item 2: " + list.getInteger(1));
System.out.println("Item 3: " + list.getBoolean(2));
查看更多
贼婆χ
3楼-- · 2020-01-26 11:00

You can somehow make use of PHP's var_export() function for this, which returns a parseable string representation of the object you want to serialize.

查看更多
姐就是有狂的资本
4楼-- · 2020-01-26 11:00

Serializing an object in PHP will dump the object properties. The resulting string isn't terribly complicated.

echo serialize(
    array(1, null, "mystring", array("key"=>"value"))
);

Results in:

a:4:{i:0;i:1;i:1;N;i:2;s:8:"mystring";i:3;a:1:{s:3:"key";s:5:"value";}}

The string identifies datatypes, array lengths, array indexes and values, string lengths... Wouldn't take too much effort to reverse-engineer it and come up with your own parser, I think.

查看更多
Rolldiameter
5楼-- · 2020-01-26 11:03

add into pom.xml

<dependency>
    <groupId>de.ailis.pherialize</groupId>
    <artifactId>pherialize</artifactId>
    <version>1.2.1</version>
</dependency>

then in code use

MixedArray list = Pherialize.unserialize(data).toArray(); // data is string `enter code here`
查看更多
何必那么认真
6楼-- · 2020-01-26 11:06

There is serialized-php-parser, which is a Java implementation that can parse php-serialized objects. In general, if you have the choice, I wouldn't recommend php-serialized as an exchange format, because it isn't ascii-safe (It contains null-bytes). Go with a format like xml or json instead. If you need a bit of type-information, xmlrpc is a good choice. It has good implementations for both php and Java.

查看更多
做个烂人
7楼-- · 2020-01-26 11:13

Note that there's a Java implementation of PHP. So you may be able to serialise the object and pass it to your Java-PHP instance, deserialise and then call into your Java infrastructure.

It all sounds a bit of an unholy mess, but perhaps worth looking at!

查看更多
登录 后发表回答