A Java library for serializing objects as PHP serialization format.

Overview

Java PHP Serializer

Build Status Coverage Status Java 7+ License

Latest release: Maven Central

A Java library for serializing objects as PHP serialization format.

The library fully implements the PHP serialization format specification, which includes:

  • Scalar values
  • Objects
  • Serializable (custom serializable objects)
  • Object and variable references

The API documentation is available on GitHub Pages more convenient viewing in browser.

A word of notice

This library does not provide any mechanism for creating a communication channel between Java and PHP. For such purpose, consider using Soluble Java.

Use case

One of the easier way to exchange data between Java and PHP consists in serializing the value to a data-interchanging format, such as JSON or XML, send it through a communication channel and finally deserialize it back to the original form on the PHP side. The problem with this approach is that the cost of deserializing complex objects in PHP is very high.

Most of the serialization libraries in PHP use reflection for re-hydrating objects, and it becomes an issue when you have to deserialize large structures with hundreds of objects. Fortunately, PHP's native serialization is fast and the unserialize() function can handle such cases in a few milliseconds.

This library implements the full format specification through a friendly API that encapsulates the complexity of the serialization process.

Installation

Maven

The PHP Serializer is available in the Maven Central repository. Any Maven based project can use it directly by adding the appropriate entries to the dependencies section of its pom.xml file:

<dependencies>
  <dependency>
    <groupId>com.marcospassos</groupId>
    <artifactId>phpserializer</artifactId>
    <version>0.8.0</version>
  </dependency>
</dependencies>

Binaries

Packaged JARs can be downloaded directly from the releases page and extracted using tar or unzip.

Usage

How to serialize data

The first step to serialize a Java object into a PHP serialization format string is to create a Serializer instance according to your application domain model. The library ships a builder that help us with this task:

Serializer serializer = new SerializerBuilder()

  // Adds a custom exclusion strategy to determine which field
  // should be serialized or not (default: no exclusion)
  .addExclusionStrategy(new MyCustomExclusionStrategy())
  
  // Sets the naming strategy to convert the name of classes
  // and fields from Java to PHP (default: PsrNamingStrategy)
  .setNamingStrategy(new MyCustomNamingStrategy())
  
  // Registers all builtin adapters, using UTF-8 for encoding strings 
  // (default: all built-in adapters, UTF-8 charset)
  .registerBuiltinAdapters()
  
  // Sets ISO-8859-1 as the default charset
  //
  // Notice that setCharset() register a new adapter configured with the 
  // specified charset. Calling setCharset() prior to registerBuiltinAdapters()
  // will have no effect as the previous configuration will get overriden
  // by the default adapter which encodes strings in UTF-8. 
  .setCharset(Charset.forName("ISO-8859-1"))
  
  // Register a custom type adapter
  .registerAdapter(CustomObject.class, new CustomObjectAdapter())
  
  // Creates the serialized based on the given configuration
  .build();

Now you have a Serializer instance configured according to your application domain model. To serialize a value, just invoke serialize(Object object) on the serializer instance:

List list = new ArrayList();
list.add("A string");
list.add(12345);
list.add(true);

// Outputs: a:3:{i:0;s:8:"A string";i:1;i:12345;i:2;b:1;}
System.out.println(serializer.serialize(list));

Naming strategies

A naming strategy allows you to translate the name of classes and fields according to the target domain model. The library ships with a built-in adapter that converts Java packages to PHP namespaces in accordance with PSR-1 rules. If the PSR strategy does not fit your needs you can easily implement a custom naming strategy. Takes as reference the following strategy that appends an underscore to all private fields:

public class UnderscoreNamingStrategy implements NamingStrategy
{
    public String getClassName(Class type)
    {
        return type.getName();
    }

    public String getFieldName(Field field)
    {
        if (Modifier.isPrivate(field.getModifiers())) {
            return "_" + field.getName();
        }

        return field.getName();
    }
}

Type Adapters

A type adapter provides the serializer the logic for how to encode a specific type. The following example shows how to create a custom type adapter to serialize Enums as string using the name of the enum constant:

public class EnumTypeAdapter implements TypeAdapter<Enum>
{
    public void write(Enum value, Writer writer, Context context)
    {
        writer.writeString(value.name());
    }
}

Notice that circular references are handled as per case basis, once it is not always the desirable. For instance, you may not want to serialize lists as objects references, as array is probably the most appropriate corresponding type in PHP. The following example shows how to handle such cases:

public class MyCustomAdapter implements TypeAdapter<CustomObject>
{
    @Override
    public void write(CustomObject object, Writer writer, Context context)
    {
        int reference = context.getReference(object);

        if (reference > 0) {
            writer.writeObjectReference(reference);

            return;
        }

        context.setReference(reference, object);

        // Custom serialization logic
    }
}

Change log

Please see CHANGELOG for more information what has changed recently.

Contributing

Contributions to the package are always welcome!

Please see CONTRIBUTING and CONDUCT for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

All contents of this package are licensed under the MIT license.

Copyright (c) 2018 Marcos Passos <[email protected]>

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
You might also like...

Transform ML models into a native code (Java, C, Python, Go, JavaScript, Visual Basic, C#, R, PowerShell, PHP, Dart, Haskell, Ruby, F#, Rust) with zero dependencies

m2cgen m2cgen (Model 2 Code Generator) - is a lightweight library which provides an easy way to transpile trained statistical models into a native cod

Jan 4, 2023

HATEOAS with HAL for Java. Create hypermedia APIs by easily serializing your Java models into HAL JSON.

hate HATEOAS with HAL for Java. Create hypermedia APIs by easily serializing your Java models into HAL JSON. More info in the wiki. Install with Maven

Oct 5, 2022

Extract text from a PDF (pdf to text). Api for PHP/JS/Python and others.

Extract text from a PDF (pdf to text). API in docker. Why did we create this project? In the Laravel project, it was necessary to extract texts from l

May 13, 2022

Share food-Android- - Food donation coded in native android with firebase, google maps api and php server xampp

Share food-Android- - Food donation coded in native android with firebase, google maps api and php server xampp

share_food-Android- Instructions: 1. Create a firebase account and link it with the project via google-services.json. 2. This project also uses a XAMP

Dec 28, 2021

Java libraries for serializing, deserializing, and manipulating JSON values

java-json-toolkit The json-toolkit repository contains the code to the following libraries: json-toolkit-text: basic library for conversion between te

Jan 26, 2022

Serializes Entities, Basically converting them to namespacedkeys that can be used later, not exactly serializing with its common definition

Serializes Entities, Basically converting them to namespacedkeys that can be used later, not exactly serializing with its common definition

Apr 3, 2022

Java serialization library, proto compiler, code generator

Java serialization library, proto compiler, code generator

A java serialization library with built-in support for forward-backward compatibility (schema evolution) and validation. efficient, both in speed and

Dec 23, 2022

Library for manually creating Java serialization data.

Library for creating Java serialization data; mainly intended for research purposes. It is not recommended to use it in production as alternative for ObjectOutputStream.

Aug 23, 2022

Ribbon is a Inter Process Communication (remote procedure calls) library with built in software load balancers. The primary usage model involves REST calls with various serialization scheme support.

Ribbon Ribbon is a client side IPC library that is battle-tested in cloud. It provides the following features Load balancing Fault tolerance Multiple

Jan 1, 2023

Screaming fast JSON parsing and serialization library for Android.

Screaming fast JSON parsing and serialization library for Android.

#LoganSquare The fastest JSON parsing and serializing library available for Android. Based on Jackson's streaming API, LoganSquare is able to consiste

Dec 18, 2022

FlatBuffers: Memory Efficient Serialization Library

FlatBuffers FlatBuffers is a cross platform serialization library architected for maximum memory efficiency. It allows you to directly access serializ

Dec 31, 2022

Ribbon is a Inter Process Communication (remote procedure calls) library with built in software load balancers. The primary usage model involves REST calls with various serialization scheme support.

Ribbon Ribbon is a client side IPC library that is battle-tested in cloud. It provides the following features Load balancing Fault tolerance Multiple

Jan 4, 2023

Jansi is a small java library that allows you to use ANSI escape sequences to format your console output which works even on windows.

Description Jansi is a small java library that allows you to use ANSI escape codes to format your console output which works even on Windows. It also

Dec 28, 2022

documents4j is a Java library for converting documents into another document format

documents4j is a Java library for converting documents into another document format. This is achieved by delegating the conversion to any

Dec 23, 2022

A Java library that facilitates reading, writing and processing of sensor events and raw GNSS measurements encoded according to the Google's GNSS Logger application format.

google-gnss-logger This library facilitates reading, writing and processing of sensor events and raw GNSS measurements encoded according to the Google

Dec 21, 2022

FST: fast java serialization drop in-replacement

FST: fast java serialization drop in-replacement

fast-serialization up to 10 times faster 100% JDK Serialization compatible drop-in replacement (Ok, might be 99% ..). As an example: Lambda Serializat

Dec 15, 2022

Java binary serialization and cloning: fast, efficient, automatic

Java binary serialization and cloning: fast, efficient, automatic

Kryo is a fast and efficient binary object graph serialization framework for Java. The goals of the project are high speed, low size, and an easy to u

Jan 5, 2023

Flash cards app using JavaFX, Scene Builder and persistence using Serialization with JAVA IO API

Flash cards app using JavaFX, Scene Builder and persistence using Serialization with JAVA IO API

Flashcards - JavaFX , Scene Builder, Serialized Persistence JAVA IO API Main Scene that will show all the Decks in Flash Card App Add or Edit Cards in

Nov 28, 2022

cglib - Byte Code Generation Library is high level API to generate and transform Java byte code. It is used by AOP, testing, data access frameworks to generate dynamic proxy objects and intercept field access.

cglib Byte Code Generation Library is high level API to generate and transform JAVA byte code. It is used by AOP, testing, data access frameworks to g

Jan 8, 2023
Comments
  • Serializing java long type to php integer

    Serializing java long type to php integer

    Hi.

    thanks for providing this serializer. Very helpful and easy to use.

    With the current implementation however, there is no builtin adapter to serialize a java long to a php Integer. Casting long to int is not a good idea and writing a custom adapter seems not possible without extending the Writer class.

    Another small issue: The documentation says, that registerBuiltinAdapters() registers all built-in adapters. That's not true. For example, the DoubleAdapter and the MapAdapter are missing.

    enhancement 
    opened by middlebrain 10
  • Writing multibyte strings

    Writing multibyte strings

    The current implementation of writeString and maybe also writeProperty and writeKey has the problem, that the length (s:<length>) of multibyte strings is not written correctly. This results on the PHP side in unserialize() [function.unserialize]: Error at offset ...

    Unfortunately, you must give the length of a serialized string in bytes instead of characters. However, the byte count depends on the character encoding.

    When testing the serializer with a servlet I didn't immediately notice this, because the standard encoding of the output is ISO-8859-1 (one character is always one byte). Only when switching to UTF-8 (response. setCharacterEncoding("UTF-8") and using german umlauts the problem came up.

    My instant fix for UTF-8 looks like this:

    Writer.java:

    ...
    import static java.nio.charset.StandardCharsets.UTF_8;
    ...
        public void writeString(String value)
        {
            setState(state.value());
    
            buffer.append("s:");
            buffer.append(value.getBytes(UTF_8).length);
            buffer.append(":\"");
            buffer.append(value);
            buffer.append("\";");
        }
    ...
    

    It would certainly be better if the desired character encoding could be given to the writer.

    Translated with www.DeepL.com/Translator.

    bug enhancement 
    opened by middlebrain 4
Releases(0.8.0)
Owner
Marcos Passos
Marcos Passos
FlatBuffers: Memory Efficient Serialization Library

FlatBuffers FlatBuffers is a cross platform serialization library architected for maximum memory efficiency. It allows you to directly access serializ

Google 19.6k Dec 31, 2022
FST: fast java serialization drop in-replacement

fast-serialization up to 10 times faster 100% JDK Serialization compatible drop-in replacement (Ok, might be 99% ..). As an example: Lambda Serializat

moru0011 1.5k Dec 15, 2022
Java binary serialization and cloning: fast, efficient, automatic

Kryo is a fast and efficient binary object graph serialization framework for Java. The goals of the project are high speed, low size, and an easy to u

Esoteric Software 5.7k Jan 5, 2023
MessagePack serializer implementation for Java / msgpack.org[Java]

MessagePack for Java MessagePack is a binary serialization format. If you need a fast and compact alternative of JSON, MessagePack is your friend. For

MessagePack 1.3k Dec 31, 2022
this project is a checker for virus's and token loggers in java apps

Rat checker this project is a checker for virus's and token loggers in java apps this project is not finished and when it is it will never be perfect.

max! 40 Sep 30, 2021
A Java Redis PubSub helper which let you send full objects without need of manual serializing

A Java Redis PubSub helper which let you send full objects without need of manual serializing

Andy 8 Nov 30, 2022
A Java serialization/deserialization library to convert Java Objects into JSON and back

Gson Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to a

Google 21.7k Jan 8, 2023
A universal types-preserving Java serialization library that can convert arbitrary Java Objects into JSON and back

A universal types-preserving Java serialization library that can convert arbitrary Java Objects into JSON and back, with a transparent support of any kind of self-references and with a full Java 9 compatibility.

Andrey Mogilev 9 Dec 30, 2021
binary serialization format

Colfer Colfer is a binary serialization format optimized for speed and size. The project's compiler colf(1) generates source code from schema definiti

Pascal S. de Kloe 680 Dec 25, 2022
Annotation processor to create immutable objects and builders. Feels like Guava's immutable collections but for regular value objects. JSON, Jackson, Gson, JAX-RS integrations included

Read full documentation at http://immutables.org // Define abstract value type using interface, abstract class or annotation @Value.Immutable public i

Immutables 3.2k Dec 31, 2022