首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将JSONObject转换为java对象

如何将JSONObject转换为java对象
EN

Stack Overflow用户
提问于 2018-10-23 04:33:39
回答 1查看 10.9K关注 0票数 2

我有一个Event类,它使用构建器模式设置字段,最后向JSON对象添加字段。

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

EventProcessor类

  public class EventProcessor{

   static{
  EventQueue eventQueue = new EventQueue<Event>();
 }

  public void addToQueue(Event event){

    eventQueue.add(event);
   }

 }

我过去常常将json传入eventProcessor.addToQueue()方法,并设置eventQueue = new EventQueue<JSONObejct>()public void addToQueue(JSONObject event)。这对我很有效。但现在我只需要将一个POJO传递给addToQueue(Event event)方法。如何更改代码并将json结果转换为event对象并将其作为参数传递给addToQueue(Event event)方法?

EN

回答 1

Stack Overflow用户

发布于 2018-10-23 05:30:35

我怀疑这是否是Builder Pattern,我的问题是,为什么要将对象解析为JSON,然后再解析回对象?不能只将对象本身传递给方法吗?就像addToQueue(this);一样?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52937380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档