Wednesday 28 October 2015

Jackson Create JSON Using JsonGenerator

JsonGenerator provides number of APIS to write JSON content. Following example explain, how to write simple employee information into employee.json file.
Step 1: Initialize JsonFactory.
JsonFactory factory = new JsonFactory();

Step 2: Get JsonGenerator from factory instance.
JsonGenerator generator = factory.createGenerator(new FileWriter(new File("employee.json")));

Step 3: Use write* methods of generator object for writing json data.

Step 4: Finally close generator.
generator.close();
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;

public class Main {
  public static void main(String args[]) throws IOException {
    JsonFactory factory = new JsonFactory();
    JsonGenerator generator = factory.createGenerator(new FileWriter(
        new File("employee.json")));

    /* Write JSON data */
    generator.writeStartObject();

    generator.writeFieldName("id");
    generator.writeString("1");

    generator.writeFieldName("firstName");
    generator.writeString("Hari krishna");

    generator.writeFieldName("lastName");
    generator.writeString("Gurram");

    generator.writeFieldName("hobbies");
    generator.writeStartArray();
    generator.writeString("Trekking");
    generator.writeString("Blogging");
    generator.writeString("Cooking");
    generator.writeEndArray();
    generator.writeEndObject();

    /* Close JsonGenerator */
    generator.close();

  }
}


# cat employee.json
{"id":"1","firstName":"Hari krishna","lastName":"Gurram","hobbies":["Trekking","Blogging","Cooking"]}



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment