简体   繁体   English

如何使用gson将树型json转换为Java对象

[英]How to convert the tree structured json to Java object using gson

 [
  {
    "sentence": "I want to buy shoes .", 
    "tree": {
      "ROOT": [
        {
          "index": 2, 
          "token": "want", 
          "label": "VERB", 
          "pos": "VBP", 
          "tree": {
            "nsubj": [
              {
                "index": 1, 
                "token": "I", 
                "label": "PRON", 
                "pos": "PRP"
              }
            ], 
            "xcomp": [
              {
                "index": 4, 
                "token": "buy", 
                "label": "VERB", 
                "pos": "VB", 
                "tree": {
                  "aux": [
                    {
                      "index": 3, 
                      "token": "to", 
                      "label": "PRT", 
                      "pos": "TO"
                    }
                  ], 
                  "dobj": [
                    {
                      "index": 5, 
                      "token": "shoes", 
                      "label": "NOUN", 
                      "pos": "NNS"
                    }
                  ]
                }
              }
            ], 
            "punct": [
              {
                "index": 6, 
                "token": ".", 
                "label": ".", 
                "pos": "."
              }
            ]
          }
        }
      ]
    }
  }
]

This is tree represented in Json. 这是Json中表示的树。 But the keys for nested nodes keep changing. 但是嵌套节点的键不断变化。
For example "ROOT, nsubj, xcomp" ... etc. 例如“ ROOT,nsubj,xcomp”等。
How do I convert above json code to Java Object using gson. 如何使用gson将上述json代码转换为Java Object。

Above response is from syntaxnet Parsey_Mcparseface api I'm trying to use. 上面的响应来自我试图使用的syntaxnet Parsey_Mcparseface api。
Thanks in advance. 提前致谢。

Gson has a method Gson#fromJson . Gson有方法Gson#fromJson For example, this is a code to read a simple String object. 例如,这是一个读取简单String对象的代码。

    Gson gson = new Gson();
    String str = gson.fromJson("\"hello\"", String.class);
    System.out.println("String: " + str);

You need to prepare Java Object to read your proposed JSON. 您需要准备Java对象以读取建议的JSON。 But, you don't need to write code by yourself. 但是,您不需要自己编写代码。 There is a website providing automatical JSON object generator. 有一个网站提供自动JSON对象生成器。

jsonschema2pojo jsonschema2pojo

enter following items: 输入以下项目:

  • Target language: Java 目标语言:Java
  • Source type: JSON 源类型:JSON
  • Annotation type: Gson 注释类型:Gson

and enter your class name, for example "ParsedSentence" 然后输入您的班级名称,例如“ ParsedSentence”

then, write code. 然后,编写代码。 You will get object. 你会得到对象。

    Gson gson = new Gson();
    ParsedSentence parsed = gson.fromJson(longLongJsonString, ParsedSentence.class);

jsonschema2pojo屏幕截图

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

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