如何使用POjo类为嵌套json创建Java对象

如何使用POjo类为嵌套json创建Java对象

本文介绍了如何使用POjo类为嵌套json创建Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在为该示例嵌套json格式生成Java对象时遇到问题

I am facing issue in generating java object for this sample nested json format

{
"Id":"id1",
"Eid":"eid1",
"tar":"pro",
"highlights":[{
  "name":"l-p"
  "Data":{
       "dataid":"did1"
       }
     },
{
  "name":"c-p",
  "Data":{
       "dataid":"did2"
       }
     },
{
  "name": "ename",
   "Data": {
       "enamedetails":"details"
}
}]
}

我已经为id,eid和tar生成了getter setter方法,但不确定如何生成高亮显示.并使用gson将其转换为json.

I have generated getter setter methods for id,eid and tar but not sure how to generate for highlights. and convert the same into json using gson.

字母设置方法:

public class hello implements intt{

       @SerializedName("ID")
       private String ID = null;

       @SerializedName("Eid")
       private String Eid=null;

       @SerializedName("tar")
       private String tar=null;
/**
       * @return the Id
       */
       public String getId() {
              return Id;
       }

       /* (non-Javadoc)
       * @see java.lang.Object#toString()
       */
       @Override
       public String toString() {
              return "EDetails [ID=" + ID
                           + ", eid=" + eid+ ", tar=" + tar
                           + "]";
       }

       /**
       * @param Id the Id to set
       */
       public void setId(String Id) {
              this.Id= Id;
       }

       /**
       * @return the eid
       */
       public String geteid() {
              return eid;
       }

       /**
       * @param eid the eid to set
       */
       public void seteid(String eid) {
              this.eid= eid;
       }

       /**
       * @return the tar
       */
       public String gettar() {
              return tar;
       }

       /**
       * @param tar the tar to set
       */
       public void settar(String tar) {
              this.tar= tar;
       }

在实现类中,

edetails.setId("id1");
edetails.settar("pro");
edetails.seteid("eid1");
 Gson gson = new Gson();
 String sDetails=gson.toJson(edetails);

不确定如何对嵌套的json类执行此操作

Not sure how to do this for nested json class

推荐答案

高亮是对象列表,因此您可以执行以下操作:

The highlights is a list of objects, so you can do this:

 public class hello implements intt{
    //other parts of class
       List<Highlight> highlights;

       public void setHighlights(List<Highlight> highlights){
          this.highlights = highlights;
         }
    }

其中Highlight是一个POJO,如下所示:

Where Highlight is a POJO like below:

public class Highlight{
  public String name;
  @SerializedName("Data")
  public Data data;
}

还有数据POJO:

public class Data{
  public String dataid;
  public String enamedetails;
}

然后,您只需创建一个列表,然后调用 setHighlights 方法.

Then you simply create a list, and call the setHighlights method.

这篇关于如何使用POjo类为嵌套json创建Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:17