简体   繁体   中英

Deserializer Json with Gson in java

I want to parse data from Json with GSon in java I have this json

    {
      "time": 3.251,
      "about_us": {
        "dc:identifier": "some string",
        "dc:title": "some string",
        "dc:contributor": [
          "1",
          "2"
        ],
        "dc:hasversion": "some string"
      },
      "results": {
        "ocw": [
          {
            "title": "some string",
            "url": "some string",
            "language": "some string",
            "university_name": "some string",
            "university_url": "some string",
            "description": "",
            "uri": "some string5",
            "similar": "some string",
            "resourceType": "OCW",
            "relatedoers": [

                    ]
          }
        ],
        "otheroer": [

        ]
      }
    }

I only need to get the "ocw" field, I am confused how to do this. I created corresponding java classes for the json objects and use @SerializedName annotations to specify the field name to grab for each data member.

The classes are as follows.

Results

Ocw

If you have this json stored in some jsonString :

    JsonObject jsonObject = (JsonObject) new JsonParser().parse(jsonString);
    JsonElement jsonElement = jsonObject.getAsJsonObject("results").getAsJsonArray("ocw").get(0);
    MyObject object = new GsonBuilder().create().fromJson(jsonElement, MyObject.class);    

MyObject should reflect this part:

        "title": "some string",
        "url": "some string",
        "language": "some string",
        "university_name": "some string",
        "university_url": "some string",
        "description": "",
        "uri": "some string5",
        "similar": "some string",
        "resourceType": "OCW",
        "relatedoers": [

                ]

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