Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 612
HenlenLee Avatar asked Feb 06 '26 00:02

HenlenLee


1 Answers

  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); 
    
like image 172
Guts Avatar answered Feb 08 '26 13:02

Guts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!