How to write json data to a file

This post explains how to write json data to a file. We will store the below json structure in the file


{
    “firstName”:”John”,
    ”lastName”:”McClane”,
    ”age”:”28″,
    ”address”:{
        “street”:”street1″,
        ”city”:”city1″,
        ”state”:”state1″,
        ”country”:”country1″,
        ”postalCode”:”12345″
    },
    "Phones":[{"Mobile":"111-111-1111"},{"Home":"222-222-2222"}]
}

Note: The output will not be formatted


package objectmodel;

import java.io.FileWriter;

import javax.json.Json;
import javax.json.JsonArrayBuilder;
import javax.json.JsonBuilderFactory;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
public class Example2 {
public static void main(String[] args) throws Exception {
    try(FileWriter fw = new FileWriter("jsondata1.txt");
    JsonWriter jsonWriter = Json.createWriter(fw);) {

        JsonBuilderFactory jsonBuilderFactory = Json.createBuilderFactory(null);

        JsonObjectBuilder jsonPhoneObjectBuilder = jsonBuilderFactory.createObjectBuilder();
        JsonObject jsonPhoneObject1 = jsonPhoneObjectBuilder.add("Mobile", "111-111-1111").build();
        JsonObject jsonPhoneObject2 = jsonPhoneObjectBuilder.add("Home", "222-222-2222").build();

        JsonObjectBuilder jsonAddressObjectBuilder = jsonBuilderFactory.createObjectBuilder();
        jsonAddressObjectBuilder.add("street", "street1");
        jsonAddressObjectBuilder.add("city", "city1");
        jsonAddressObjectBuilder.add("state", "state1");
        jsonAddressObjectBuilder.add("country", "country1");
        jsonAddressObjectBuilder.add("postalCode", "12345");

        JsonArrayBuilder jsonArrayBuilder = jsonBuilderFactory.createArrayBuilder();
        jsonArrayBuilder.add(jsonPhoneObject1);
        jsonArrayBuilder.add(jsonPhoneObject2);

        JsonObjectBuilder jsonObjectBuilder = jsonBuilderFactory.createObjectBuilder();
        jsonObjectBuilder.add("firstName", "John");
        jsonObjectBuilder.add("lastName", "McClane");
        jsonObjectBuilder.add("age", "28");
        jsonObjectBuilder.add("address", jsonAddressObjectBuilder);
        jsonObjectBuilder.add("Phones", jsonArrayBuilder);

        JsonObject jsonObject = jsonObjectBuilder.build();

        jsonWriter.writeObject(jsonObject);
    }
}

Output

{“firstName”:”John”,”lastName”:”McClane”,”age”:”28″,”address”:{“street”:”street1″,”city”:”city1″,”state”:”state1″,”country”:”country1″,”postalCode”:”12345″},”Phones”:[{“Mobile”:”111-111-1111″},{“Home”:”222-222-2222″}]}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s