Saturday 22 February 2020

org json: Pretty Print json

JSONObject class provides toString method, it takes an integer as argument (it represents indentation factor) and return the pretty print json string.

Example
JSONObject jsonObject = new JSONObject(emp);
String prettyJson = jsonObject.toString(4);

Find the below working application.

Organization.java
package com.sample.app.model;

public class Organization {
 private String name;
 private float yrsOfExperience;

 public Organization(String name, float yrsOfExperience) {
  this.name = name;
  this.yrsOfExperience = yrsOfExperience;
 }

 public String getName() {
  return name;
 }

 public float getYrsOfExperience() {
  return yrsOfExperience;
 }

 public void setName(String name) {
  this.name = name;
 }

 public void setYrsOfExperience(float yrsOfExperience) {
  this.yrsOfExperience = yrsOfExperience;
 }

}

Employee.java
package com.sample.app.model;

import java.util.ArrayList;
import java.util.List;

public class Employee {
 private List<Organization> org = new ArrayList<Organization>();
 private String firstName;
 private String lastName;
 private double salary;

 public Employee(String firstName, String lastName, double salary, List<Organization> org) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.salary = salary;
  this.org = org;
 }

 public String getFirstName() {
  return firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public List<Organization> getOrg() {
  return org;
 }

 public double getSalary() {
  return salary;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public void setOrg(List<Organization> org) {
  this.org = org;
 }

 public void setSalary(double salary) {
  this.salary = salary;
 }

}

App.java
package com.sample.app;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import com.sample.app.model.Employee;
import com.sample.app.model.Organization;

public class App {

 public static void main(String args[]) {
  List<Organization> organizations = new ArrayList<Organization>();
  Organization o1 = new Organization("Honeywell", 2.2f);
  Organization o2 = new Organization("IBM", 1.8f);
  organizations.add(o1);
  organizations.add(o2);

  Employee emp = new Employee("Krishna", "Hari", 80000, organizations);

  JSONObject jsonObject = new JSONObject(emp);
  String prettyJson = jsonObject.toString(4);

  System.out.println(prettyJson);
 }
}

Output

{
    "firstName": "Krishna",
    "lastName": "Hari",
    "org": [
        {
            "yrsOfExperience": 2.2,
            "name": "Honeywell"
        },
        {
            "yrsOfExperience": 1.8,
            "name": "IBM"
        }
    ],
    "salary": 80000
}




Previous                                                    Next                                                    Home

No comments:

Post a Comment