Android: Serialization guide

📘

This guide is mainly focused on Android (Kotlin/Java).

Data serialization

When using custom events and global event properties you may need to serialize the data to one of SDK’s supported formats:

  • JSONObject
  • Bundle
  • json String

For all examples we going to use this data class as an input to the serialization:

data class Employee(
    val name: String,
    val id: String,
    val salary: Double
)
public class Employee {
    private String name;
    private String id;
    private double salary;

    public Employee(String name, String id, double salary) {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public String getId() {
        return id;
    }

    public double getSalary() {
        return salary;
    }
}

Serialize as an JSONObject

val employee = Employee("John Dough", "#123456", 1000)

val serializedEmployee = JSONObject()
    .put("name", employee.name)
    .put("id", employee.id)
    .put("salary", employee.salary)
Employee employee = new Employee("John Dough", "#123456", 1000);

JSONObject serializedEmployee = new JSONObject();

try {
    serializedEmployee.put("name", employee.name);
    serializedEmployee.put("id", employee.id);
    serializedEmployee.put("salary", employee.salary);
} catch (JSONException e) {
    e.printStackTrace();
}

Serialize as a Bundle

val employee = Employee("John Dough", "#123456", 1000)

val serializedEmployee = bundleOf(
    "name" to employee.name,
    "id" to employee.id,
    "salary" to employee.salary
)
Employee employee = new Employee("John Dough", "#123456", 1000);

Bundle serializedEmployee = new Bundle();
serializedEmployee.putString("name", employee.name);
serializedEmployee.putString("id", employee.id);
serializedEmployee.putDouble("salary", employee.salary);

Serialize as a json String

If you are using Gson (or any other similar library) you might prefer this way of serializing data for SDK API methods.

val employee = Employee("John Dough", "#123456", 1000)
val serializedEmployee = gson.toJson(employee)
Employee employee = new Employee("John Dough", "#123456", 1000);
String serializedEmployee = gson.toJson(employee);