How to convert JSONObject to java object

11,949
  1. You can use Gson to convert JSONObject to java POJO:

    Event event = gson.fromJson(json.toString(), Event.class);
    
  2. You can use Jackson to do the same:

    ObjectMapper objectMapper = new ObjectMapper();
    Event event = objectMapper.readValue(json.toString(), Event.class); 
    
Share:
11,949
HenlenLee
Author by

HenlenLee

Updated on July 12, 2022

Comments

  • HenlenLee
    HenlenLee almost 2 years

    I have an Event class which uses the builder pattern to set fields and finally adds fields to a JSON object.

    public class Event{
    
      private EventProcessor eventProcessor = new EventProcessor();
      private String userName;
      private String userID;
    
      public Event setUserName(String userName){
         this.userName = userName;
         return this;
      }
      public Event setUserID(String userID){
         this.userID = userID;
         return this;
    }
    
      public void toJson(){
       JSONObject json = new JSONObject();
    
       if(null != userName)
       json.put("userName", userName);
       if(null != userID)
       json.put("userID", userID);
    
      // need help to convert json to "event"
       eventProcessor.addToQueue(event);
      }
     }
    

    The EventProcessor class

      public class EventProcessor{
    
       static{
      EventQueue eventQueue = new EventQueue<Event>();
     }
    
      public void addToQueue(Event event){
    
        eventQueue.add(event);
       }
    
     }
    

    I used to pass json into eventProcessor.addToQueue() method and set eventQueue = new EventQueue<JSONObejct>() and public void addToQueue(JSONObject event). This works for me. But now I need to just pass a POJO to the addToQueue(Event event) method. How can I change the code and convert the json result to event object and pass it as a parameter to the addToQueue(Event event) method?