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.
-
Implements
BorshBuffer
on top of Java'sByteBuffer
. -
Implements
BorshReader
on top of any JavaInputStream
. -
Implements
BorshWriter
on top of any JavaOutputStream
. -
Provides
BorshField
with order parameter for including and sorting POJO fields. -
Provides
BorshSubTypes
andBorshSubType
for supporting serialization of interface implementations. -
Based on Java NIO, enabling high-performance, zero-copy interoperability with native code via JNI.
-
GC friendly: avoids unnecessary copying wherever possible.
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/syntifi/borshj.git
cd borshj
gradle jar
ls -l build/libs/borshj-$(cat VERSION).jar
To use the Borsh object serializer/deserializer, you need add just one import:
import com.syntifi.near.borshj.Borsh;
The following code examples further below are all predicated on this simple data class definition:
public class Point2D implements Borsh {
@BorshField(order = 1)
public float x;
@BorshField(order = 2)
public float y;
public Point2D() {}
public Point2D(float x, float y) {
this.x = x;
this.y = y;
}
}
NOTE: Only non-transient and annotated fields with
BorshField
will be serialized.
To serialize a POJO, use the Borsh.serialize()
method:
Point2D point = new Point2D(123.0, 456.0);
byte[] bytes = Borsh.serialize(point);
To deserialize a POJO, use the Borsh.deserialize()
method:
Point2D point = Borsh.deserialize(bytes, Point2D.class);
Borsh | Java | TypeScript |
---|---|---|
u8 integer |
byte |
number |
u16 integer |
short |
number |
u32 integer |
int |
number |
u64 integer |
long |
BN |
u128 integer |
BigInteger |
BN |
f32 float |
float |
N/A |
f64 float |
double |
N/A |
fixed-size byte array | byte[] |
Uint8Array |
UTF-8 string | String |
string |
option | Optional |
null or type |
map | Map |
N/A |
set | Set |
N/A |
structs | Object |
any |
enum | Enum |
- |
subtypes | interface |
- |
Classes used with Borsh.deserialize()
must have a nullary default constructor
because instances of the class will be instantiated through Java's
reflection API.