简体   繁体   中英

How to write nested JSON using Jackson?

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!

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM