HenlenLee
HenlenLee

Reputation: 445

How to convert JSONObject to java object

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?

Upvotes: 3

Views: 18376

Answers (2)

Guts
Guts

Reputation: 768

  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); 
    

Upvotes: 5

Bleach
Bleach

Reputation: 309

I doubt that this is a Builder Pattern yet, my question is why are you parsing the object into a JSON and back to the object again? Cannot you just past the object itself to the method? Like addToQueue(this); ?

Upvotes: 0

Related Questions