Java convert object to JSON string example using Gson toJson() method

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. Lot of applications have started using JSON for data interchange rather than using XML specially JavaScript frameworks such as ExtJs, jQuery etc. It's the ease of converting Object notations to JSON and vice versa makes it really compelling.

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. Please go ahead and download Gson library and add to your your project CLASSPATH if you haven't done so. Here is the link

http://code.google.com/p/google-gson/downloads/list

In this example we are going to learn about the toJson() method that will help us convert a Java Object to JSON String. This sample Java program generates a JSON String from the Java Object and then saves it to a file. You can choose to send your JSON String data as HTTP response to some AJAX request.

Java source code for converting an Object to JSON String

package com.as400samplecode;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import com.as400samplecode.util.OrderDetail;
import com.as400samplecode.util.OrderHeader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class GenerateJSON {

 public static void main(String[] args) {

  OrderHeader orderHeader = new OrderHeader();
  orderHeader.setCustomerId("CUST01");
  orderHeader.setOrderId("101010");
  orderHeader.setOrderTotal(99.99);

  ArrayList<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();

  OrderDetail orderDetail = new OrderDetail();
  orderDetail.setLineId("1");
  orderDetail.setItemNumber("ABC");
  orderDetail.setQuantity(9);
  orderDetail.setPrice(10.00);
  orderDetailList.add(orderDetail);

  orderDetail = new OrderDetail();
  orderDetail.setLineId("2");
  orderDetail.setItemNumber("XYZ");
  orderDetail.setQuantity(1);
  orderDetail.setPrice(9.99);
  orderDetailList.add(orderDetail);

  orderHeader.setOrderDetailList(orderDetailList);

  Gson gson = new GsonBuilder().setPrettyPrinting().create();
  //you don't need the GsonBuilder if you are just sending the 
  //data to another system or AJAX response, in that case just use
  //Gson gson = new Gson();
  
  // convert java object to JSON format, so easy
  String jsonString = gson.toJson(orderHeader);
  
  //write the JSON data to file
  BufferedWriter bufferedWriter = null;
  try {

   File file = new File("data/myFile.json");
   if(!file.exists()){
      file.createNewFile();
         }
 
         FileWriter fileWriter = new FileWriter(file);
         bufferedWriter = new BufferedWriter(fileWriter);
         bufferedWriter.write(jsonString);
        
    
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (bufferedWriter != null){
     bufferedWriter.close();
    }
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  }

 }

}


Java source code for OrderHeader Object

package com.as400samplecode.util;

import java.util.ArrayList;

public class OrderHeader {
 
 String customerId = null;
 String orderId = null;
 Double orderTotal = null;
 ArrayList<OrderDetail> orderDetailList;
 
 public String getCustomerId() {
  return customerId;
 }
 public void setCustomerId(String customerId) {
  this.customerId = customerId;
 }
 public String getOrderId() {
  return orderId;
 }
 public void setOrderId(String orderId) {
  this.orderId = orderId;
 }
 public Double getOrderTotal() {
  return orderTotal;
 }
 public void setOrderTotal(Double orderTotal) {
  this.orderTotal = orderTotal;
 }
 public ArrayList<OrderDetail> getOrderDetailList() {
  return orderDetailList;
 }
 public void setOrderDetailList(ArrayList<OrderDetail> orderDetailList) {
  this.orderDetailList = orderDetailList;
 }

}


Java source code for OrderDetail Object

package com.as400samplecode.util;

public class OrderDetail {
 
 String lineId = null;
 String itemNumber = null;
 int quantity = 0;
 Double price = null;
 
 public String getLineId() {
  return lineId;
 }
 public void setLineId(String lineId) {
  this.lineId = lineId;
 }
 public String getItemNumber() {
  return itemNumber;
 }
 public void setItemNumber(String itemNumber) {
  this.itemNumber = itemNumber;
 }
 public int getQuantity() {
  return quantity;
 }
 public void setQuantity(int quantity) {
  this.quantity = quantity;
 }
 public Double getPrice() {
  return price;
 }
 public void setPrice(Double price) {
  this.price = price;
 }

}


JSON String output in myFile.json

{
  "customerId": "CUST01",
  "orderId": "101010",
  "orderTotal": 99.99,
  "orderDetailList": [
    {
      "lineId": "1",
      "itemNumber": "ABC",
      "quantity": 9,
      "price": 10.0
    },
    {
      "lineId": "2",
      "itemNumber": "XYZ",
      "quantity": 1,
      "price": 9.99
    }
  ]
}

Recommended Reading

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.