JSON Generator Salesforce | JsonGenerator Class | Techila Global Service
single,single-post,postid-2836,single-format-standard,ajax_updown_fade,page_not_loaded,,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,qode-content-sidebar-responsive,qode-theme-ver-9.4.2,bridge,wpb-js-composer js-comp-ver-4.12,vc_responsive

JSON Generator


JSON Generator

Using the JSONGenerator class methods, you can generate standard JSON-encoded content.

You can construct JSON content, element by element, using the standard JSON encoding. To do so, use the methods in the JSONGenerator class.

JSONGenerator Sample

This example generates a JSON string in pretty print format by using the methods of the JSONGenerator class. The example first adds a number field and a string field, and then adds a field to contain an object field of a list of integers, which gets deserialized properly. Next, it adds the A object into the Object A field, which also gets deserialized.

public class JSONGeneratorSample{
    public class A {
        String str;
        public A(String s) { str = s; }
    static void generateJSONContent() {
        // Create a JSONGenerator object.
        // Pass true to the constructor for pretty print formatting.
        JSONGenerator gen = JSON.createGenerator(true);
        // Create a list of integers to write to the JSON string.
        List<integer> intlist = new List<integer>();
        // Create an object to write to the JSON string.
        A x = new A('X');
        // Write data to the JSON string.
        gen.writeNumberField('abc', 1.21);
        gen.writeStringField('def', 'xyz');
        gen.writeObjectField('aaa', intlist);
        gen.writeFieldName('Object A');
        // Get the JSON string.
        String pretty = gen.getAsString();
        System.assertEquals('{\n' +
        '  "abc" : 1.21,\n' +
        '  "def" : "xyz",\n' +
        '  "ghi" : {\n' +
        '    "aaa" : [ 1, 2, 3 ]\n' +
        '  },\n' +
        '  "Object A" : {\n' +
        '    "str" : "X"\n' +
        '  }\n' +
        '}', pretty);

JSONGenerator Class

Contains methods used to serialize objects into JSON content using the standard JSON encoding.

The System.JSONGenerator class is provided to enable the generation of standard JSON-encoded content and gives you more control on the structure of the JSON output.

JSONGenerator Methods

The following are methods for JSONGenerator. All are instance methods.

“Explore – Techila Global Services, A Salesforce development company”

Author: techila

No Comments

Post A Comment