Convert Values and Records to JSON and XML

This example shows how to turn records, lists and single values into JSON and XML text. Every ValueNode can render itself with toJson() and toXml(), and Record is itself a ValueNode. Plain Java objects are wrapped with ValueNode.from(): collections and arrays become an ArrayValue, any other object becomes a SingleValue, and a value that already is a ValueNode is returned as-is, so a record is never wrapped.

Java Code Listing

package com.northconcepts.datapipeline.examples.cookbook;

import java.math.BigDecimal;
import java.util.Arrays;

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

public class ConvertValuesAndRecordsToJsonAndXml {

    public static void main(String[] args) {
        Record record = new Record()
                .setField("Account", 101)
                .setField("Name", "Keanu Reeves");

        System.out.println(record.toJson());
        System.out.println(record.toXml());

        ValueNode tags = ValueNode.from(Arrays.asList("vip", "early-adopter"));
        System.out.println(tags.toJson());
        System.out.println(tags.toXml());

        ValueNode balance = ValueNode.from(new BigDecimal("9315.45"));
        System.out.println(balance.toJson());
        System.out.println(balance.asSingleValue().getValueAsString());
    }

}

Code Walkthrough

  1. A Record is created with an integer Account field and a string Name field. toJson() renders it as a JSON object, keeping the number unquoted, and toXml() renders it as a <document> element with one child element per field.
  2. ValueNode.from(Arrays.asList(...)) wraps the list in an ArrayValue. toJson() renders a JSON array and toXml() a <document> element with one <single_value> child per item.
  3. ValueNode.from(new BigDecimal("9315.45")) wraps the number in a SingleValue. toJson() prints the bare number, and asSingleValue().getValueAsString() returns its text form.

Console Output

{"Account":101,"Name":"Keanu Reeves"}
<?xml version='1.0' encoding='UTF-8'?><document><Account>101</Account><Name>Keanu Reeves</Name></document>
["vip","early-adopter"]
<?xml version='1.0' encoding='UTF-8'?><document><single_value>vip</single_value><single_value>early-adopter</single_value></document>
9315.45
9315.45
Mobile Analytics