How to write nested JSON using Jackson?

2019-07-14 09:10发布

Currently I am trying to automate JSON APIs through Java code.. I have run the JSON successfully without nesting.. Now in our API, there are nested JSON, which I need to automate through POJO... How can I do it..

One API worked for me which has single parameter.

JSON for the API

{
    "userId": 1

  },

JAVA Class for it.

   public class Post {

        @JsonProperty("userId")
        private String userId;          
        public String getUserId()
        {
           return userId;
        }

        public void setUserId(String userId) 
        {       
            this.userId = userId;   
        }

 }

Now I have an API which has multiple nested parameters.. How to create Java class for the same?

Nested JSON

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

How can I write Java class for this?

Thanks in advance!

2条回答
贼婆χ
2楼-- · 2019-07-14 09:57

You need to replicate your JSON structure with Java classes. In your case it should be something like:

public class Glossary {
       String title;
       GlossDiv glossDiv;
       {getters, setters}
}

public class GlossDiv {
       String title;
       GlossList glossList;

       public getGlossList() {
             return glossList;
       }

       public setGlossList(GlossList glossList) {
             this.glossList = glossList;
       }
}

And so on, for each nested object.

查看更多
我想做一个坏孩纸
3楼-- · 2019-07-14 10:03

use link to convert your json to java class, just paste your json here n download class structure.

You can access nested json field by using . (dot) operator

Ex: if you want access ID from GlossEntry use following code

  ObjectMapper mapper = new ObjectMapper();
  String jsonString="";
  Glossary_ sc=mapper.readValue(jsonString,Glossary_.class);

System.out.println("ID:"+sc.getGlossDiv().getGlossList().getGlossEntry().getID());
查看更多
登录 后发表回答