How to convert JSONObject to java object
11,949
You can use Gson to convert JSONObject to java POJO:
Event event = gson.fromJson(json.toString(), Event.class);
You can use Jackson to do the same:
ObjectMapper objectMapper = new ObjectMapper(); Event event = objectMapper.readValue(json.toString(), Event.class);
Author by
HenlenLee
Updated on July 12, 2022Comments
-
HenlenLee almost 2 years
I have an
Event
class which uses the builder pattern to set fields and finally adds fields to aJSON
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
intoeventProcessor.addToQueue()
method and seteventQueue = new EventQueue<JSONObejct>()
andpublic void addToQueue(JSONObject event)
. This works for me. But now I need to just pass a POJO to theaddToQueue(Event event)
method. How can I change the code and convert thejson
result toevent
object and pass it as a parameter to theaddToQueue(Event event)
method?-
Akash Agarwal over 5 yearsPossible duplicate of How can i convert JSON to JAVA object?
-