Reputation: 810
I have an array in php of this format:
<?php
$value = array("id" => 42, "user" => "superman");
echo serialize($value);
?>
Serialized :
a:2:{s:2:"id";i:42;s:4:"user";s:8:"superman";}
I receive this into a String
in java.
How I can do for deserialize this in java ?
I know the implements Serializable
in java but not work in this case.
I want to create an object in this kind of format :
import java.io.Serializable;
public class Serial implements Serializable{
private int mId;
private String mUser;
public Serial(int mId, String mUser) {
super();
this.mId = mId;
this.mUser = mUser;
}
public int getId() {
return mId;
}
public void setId(int id) {
this.mId = id;
}
public String getUser() {
return mUser;
}
public void setUser(String user) {
this.mUser = user;
}
}
After that I want to create another time the String
serialized from the Java object for deserialize in PHP;
Thanks for your help.
Upvotes: 3
Views: 6501
Reputation: 1204
A bit late for you, but could be useful for others (including me) :
You can check this question, which has a lot of answers. For those who don't have time to read, here are the main links it leads to :
1- A static class for PHP de/serialization
2- The Pherialize class with its satellite classes
BUT as @Robadob (and all devs) said it, the most reliable method to do this kind of job is to use a standard format.
Upvotes: 2
Reputation: 5349
You can't natively read one languages serialised objects with another language (languages each have their own serialisation protocols/format, there is no guarantee they can read one-anothers format), Java serialised objects are serialised to a binary format and PHP your provided text format.
There are libraries such as Google's protocol buffers that you can use, they don't officially support PHP, however there are 3rd party libraries which provide Protocol Buffer support for PHP.
Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages – Java, C++, or Python.
If you aren't fond of that, you will need to develop your own protocol for reading PHPs serialised objects into a Java object, you may be able to do this with a modified JSON library as I don't believe that s:2:"id";
from your sample serialised object is valid JSON. There exists a library for doing this using Java, however the PHP serialisation format isn't 'safe' as it can contain null values, so I would advise against it.
Upvotes: 3