1

How to create javabean for gson for the below JSON script?

{
    "header": [
        {
            "title": {
                "attempts": 3,
                "required": true
            }
        },
        {
            "on": {
                "next": "abcd",
                "event": "continue"
            }
        },
        {
            "on": {
                "next": "",
                "event": "break"
            }
        }
    ]
}

I'm trying to build the javabean for this JSON output. I'm not able to repeat the fieldname on.

Please suggest any solutions.

3
  • Ok, what is your question ? Commented Jul 20, 2015 at 11:31
  • i want to build the above json script through gson. For this i am not able to create the java bean Commented Jul 20, 2015 at 11:34
  • i am getting the error multiple field name with "no" Commented Jul 20, 2015 at 11:36

1 Answer 1

1

You will need multiple classes to accomplish this. I made some assumptions with the naming, but these should suffice:

public class Response {
    private List<Entry> header;

    private class Entry {
        private Title title;
        private On on;
    }

    private class Title {
        int attempts;
        boolean required;
    }

    private class On {
        String next, event;
    }
}

You can test it with a main() method like:

public static void main(String[] args) {
    // The JSON from your post
    String json = "{\"header\":[{\"title\":{\"attempts\":3,\"required\":true}},{\"on\":{\"next\":\"abcd\",\"event\":\"continue\"}},{\"on\":{\"next\":\"\",\"event\":\"break\"}}]}";

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    Response response = gson.fromJson(json, Response.class);

    System.out.println(response.header.get(0).title.attempts); // 3
    System.out.println(response.header.get(1).on.next); // abcd
    System.out.println(gson.toJson(response)); // Produces the exact same JSON as the original
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.