Serialize RecordList to and from JSON

Updated: Oct 30, 2023

This example shows how to convert a RecordList to JSON and vice versa. You can use this functionality to store datasets on disk or transmit them over a network to a REST API. 

 

Java Code Listing

package com.northconcepts.datapipeline.examples.cookbook;

import com.northconcepts.datapipeline.core.Record;
import com.northconcepts.datapipeline.core.RecordList;

import java.io.*;
import java.math.BigInteger;
import java.nio.file.Files;

public class SerializeRecordListFromToJson {
    public static void main(String[] args) throws IOException {
        Record record1 = new Record();
        record1.setField("name", "John Wayne");
        record1.setField("balance", new BigInteger("1234567894"));

        Record record2 = new Record();
        record2.setField("name", "Peter Parker");
        record2.setField("balance", new BigInteger("9876543210"));

        RecordList recordList = new RecordList(record1, record2);
        recordList.toJson(new FileWriter("example/data/output/name-balance.json"));
        System.out.println("Serialization of record list to JSON file completed");

        RecordList recordList1 = new RecordList();
        recordList1.fromJson(Files.newInputStream(new File("example/data/output/name-balance.json").toPath()));
        System.out.println("Deserialization of record list from JSON file completed");
        System.out.println(recordList1);
    }
}

 

Code Walkthrough

  1. First, two Record instances are created to store fields as a key-value pair.
  2. record1.setField() creates a field with the name specified in the first parameter and the value specified in the specified second parameter.
  3. RecordList is created to store the two records created in the previous steps.
  4. RecordList class comes with methods toJson() and fromJson() to make conversions between RecordList and JSON. In the example, the produced JSON text is written to the output file name-balance.json and recreated from that to RecordList instance again.

 

Console output

Serialization of record list to JSON file completed
Deserialization of record list from JSON file completed
RecordList [records=[
        Record (MODIFIED) (is child record) {
            0:[name]:STRING=[John Wayne]:String
            1:[balance]:LONG=[1234567894]:Long
        }, 
        Record (MODIFIED) (is child record) {
            0:[name]:STRING=[Peter Parker]:String
            1:[balance]:LONG=[9876543210]:Long
        }]]
Mobile Analytics