Home

Awesome

BorshJ

Project license Discord

BorshJ is an implementation of the Borsh binary serialization format for Java (and Kotlin, Scala, Clojure, Groovy, Jython, JRuby, etc.) projects.

Borsh stands for Binary Object Representation Serializer for Hashing. It is meant to be used in security-critical projects as it prioritizes consistency, safety, speed, and comes with a strict specification.

Features

Prerequisites

Installation

We are working on building release binaries. They will be available here soon.

In the meantime, if you wish to try out BorshJ, you will need to build the JAR file from source code yourself:

git clone https://github.com/near/borshj.git

cd borshj

gradle jar

ls -l build/libs/borshj-$(cat VERSION).jar

Usage

To use the Borsh object serializer/deserializer, you need add just one import:

import org.near.borshj.Borsh;

Examples

The following code examples further below are all predicated on this simple data class definition:

public class Point2D implements Borsh {
  public float x;
  public float y;

  public Point2D() {}

  public Point2D(float x, float y) {
    this.x = x;
    this.y = y;
  }
}

Serializing an object

To serialize a POJO, use the Borsh.serialize() method:

Point2D point = new Point2D(123.0, 456.0);

byte[] bytes = Borsh.serialize(point);

Deserializing an object

To deserialize a POJO, use the Borsh.deserialize() method:

Point2D point = Borsh.deserialize(bytes, Point2D.class);

Type Mappings

BorshJavaTypeScript
u8 integerbytenumber
u16 integershortnumber
u32 integerintnumber
u64 integerlongBN
u128 integerBigIntegerBN
f32 floatfloatN/A
f64 floatdoubleN/A
fixed-size byte arraybyte[]Uint8Array
UTF-8 stringStringstring
optionOptionalnull or type
mapMapN/A
setSetN/A
structsObjectany

Frequently Asked Questions

Q: Why does my class need a default constructor?

Classes used with Borsh.deserialize() must have a nullary default constructor because instances of the class will be instantiated through Java's reflection API.