简体   繁体   中英

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. But the keys for nested nodes keep changing.
For example "ROOT, nsubj, xcomp" ... etc.
How do I convert above json code to Java Object using gson.

Above response is from syntaxnet Parsey_Mcparseface api I'm trying to use.
Thanks in advance.

Gson has a method Gson#fromJson . For example, this is a code to read a simple String object.

    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. But, you don't need to write code by yourself. There is a website providing automatical JSON object generator.

jsonschema2pojo

enter following items:

  • Target language: Java
  • Source type: JSON
  • Annotation type: Gson

and enter your class name, for example "ParsedSentence"

then, write code. You will get object.

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

jsonschema2pojo屏幕截图

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