Saturday 16 March 2019

JSONObject: Convert java object to json string


By passing Java object to JSONObject constructor, you can construct JSONObject from a java object.

Example
JSONObject jsonObject = new JSONObject(emp);

Employee.java
package com.sample;

public class Employee {
 private String name;
 private String organization;
 private int id;

 
 public String getName() {
  return name;
 }

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

 public String getOrganization() {
  return organization;
 }

 public void setOrganization(String organization) {
  this.organization = organization;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

}


App.java

package com.sample;

import org.json.JSONObject;

public class App {

 public static void main(String args[]) {
  Employee emp = new Employee();
  emp.setId(123);
  emp.setName("Krishna");
  emp.setOrganization("ABC Corporation");

  JSONObject jsonObject = new JSONObject(emp);

  System.out.println("name : " + jsonObject.get("name"));
  System.out.println("id : " + jsonObject.get("id"));
  System.out.println("organization : " + jsonObject.get("organization"));
  
  System.out.println("Json String : " + jsonObject);

 }
}

Output
name : Krishna
id : 123
organization : ABC Corporation
Json String : {"organization":"ABC Corporation","name":"Krishna","id":123}



Previous                                                 Next                                                 Home

No comments:

Post a Comment