简体   繁体   English

如何使用Jackson编写嵌套的JSON?

[英]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.. 目前我正在尝试通过Java代码自动化JSON API。我已经成功运行了JSON而没有嵌套。现在在我们的API中,有嵌套的JSON,我需要通过POJO自动化...我该怎么做...

One API worked for me which has single parameter. 一个API适用于我,它有单个参数。

JSON for the API API的JSON

{
    "userId": 1

  },

JAVA Class for it. JAVA类吧。

   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? 现在我有一个API,它有多个嵌套参数..如何创建相同的Java类?

Nested JSON 嵌套的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? 我怎么能为此编写Java类?

Thanks in advance! 提前致谢!

use link to convert your json to java class, just paste your json here n download class structure. 使用link将你的json转换为java类,只需将你的json粘贴到这里下载类结构。

You can access nested json field by using . 您可以使用访问嵌套的json字段。 (dot) operator (点)运算符

Ex: if you want access ID from GlossEntry use following code 例如:如果您想要从GlossEntry获取访问ID使用以下代码

  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. 您需要使用Java类复制JSON结构。 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. 依此类推,对于每个嵌套对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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