Saturday, 16 March 2019

JSONObject: Create JSONObject from map


You can construct JSONObject from map by passing the map to JSONObject constructor.

Example
Map<String, Object> map = new HashMap<> ();

map.put("id", 123);
map.put("name", "Krishna");
map.put("organization", "ABC Corporation");

JSONObject jsonObject = new JSONObject(map);

App.java
package com.sample;

import org.json.JSONObject;
import java.util.*;

public class App {

 public static void main(String args[]) {
  Map<String, Object> map = new HashMap<> ();
  
  map.put("id", 123);
  map.put("name", "Krishna");
  map.put("organization", "ABC Corporation");

  JSONObject jsonObject = new JSONObject(map);

  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 : {"name":"Krishna","organization":"ABC Corporation","id":123}



Previous                                                 Next                                                 Home

No comments:

Post a Comment