Abubakkar
Abubakkar

Reputation: 15664

Pasring jira json using GSON

I have parsed all my data using GSON except this one giving me trouble.

I have JSON data like (for Issue java pojo) :

    "issue": {
    "id": "44544",
    "self": "http://jira.webaroo.com/rest/api/2/issue/44544",
    "key": "BIZSOL-166",
    "fields": {
        "summary": "Jira Wrapper Implementation - Test",
        "issuetype": {
            "self": "http://jira.webaroo.com/rest/api/2/issuetype/2",
            "id": "2",
            "description": "A new feature of the product, which has yet to be developed.",
            "iconUrl": "http://jira.webaroo.com/images/icons/issuetypes/newfeature.png",
            "name": "New Feature",
            "subtask": false
        },
        "votes": {
            "self": "http://jira.webaroo.com/rest/api/2/issue/BIZSOL-166/votes",
            "votes": 0,
            "hasVoted": false
        },
        "resolution": null,
        "fixVersions": [],
        "resolutiondate": null,
        "customfield_11101": null
    }
}

I have my java class as Issue.java :

protected String key;
protected String summary;
protected IssueType issuetype;
protected Votes votes;
protected Resolution resolution;
protected List<FixVersions> fixVersions;
protected Date resolutiondate;

I am able to get key value from GSON conversion.

But I am not able to get other data.

I know that its not coming because they are part of "fields" structure but I don't want to define "fields" structure in my java.

I directly want to get one-level down values.

Please help me in achieving this using GSON. I am fairly new to GSON.

Upvotes: 2

Views: 772

Answers (1)

Maybe a little late but for WIT

you can parse the json into a json object and then get the elements by the key name.

public static void main(String[] args) throws FileNotFoundException {
Gson gson = new Gson();
JsonParser prser = new JsonParser();
JsonReader file = new JsonReader(new FileReader("./file.txt"));
JsonObject result = prser.parse(file).getAsJsonObject();
System.out.println(result.get("issue").getAsJsonObject().get("id"));
System.out.println(result.get("issue").getAsJsonObject().get("key"));
System.out.println(result.get("issue").getAsJsonObject().get("fields").getAsJsonObject().get("votes")
    .getAsJsonObject().get("self"));
}

the result will be:

"44544"

"BIZSOL-166"

"http://jira.webaroo.com/rest/api/2/issue/BIZSOL-166/votes"

the only thing you have to be care of is the nested keys... example: id is a child from issue, so you will have to get 1st that parent and navigate deep until you find the element you want

You can for sure define a set as:

Set<Map.Entry<String, JsonElement>> entrySet = result.entrySet(); 

Upvotes: 1

Related Questions