1

I need to build a below JSON programmatically. But,need a elegant way to convert from Java object to JSON. so that, i can avoid string builder to build the below JSON.

I aware of that, sometimes,I have array of parameters for the specific key while building JSON. Please share the generic way to solve that.

Please share some thoughts to this.

{
    "tropo": [
        {
            "ask": {
                "attempts": 3,
                "say": [
                    {
                        "value": "Hi.",
                        "event": "timeout"
                    },
                    {
                        "value": "Hello",
                        "event": "nomatch:1"
                    },
                    {
                        "value": "Hello2",
                        "event": "nomatch:2"
                    },
                    {
                        "value": "Satheesh",
                        "voice": "veronica"
                    }
                ],
                "choices": {
                    "value": "Yes(1,Yes),No(2,No)",
                    "mode": "ANY"
                },
                "voice": "veronica",
                "recognizer": "en-us",
                "timeout": 8,
                "name": "year",
                "minConfidence": 39,
                "required": true
            }
        },
        {
            "on": {
                "next": "https://test.app.com/WAP2/",
                "event": "continue"
            }
        },
        {
            "on": {
                "next": "https://test.app.com/WAP2/",
                "event": "incomplete"
            }
        },
        {
            "on": {
                "next": "",
                "event": "hangup"
            }
        }
    ]
}
1
  • you can use GSON Library. Commented Jul 20, 2015 at 7:01

1 Answer 1

2

As paulsm4 said, I'd have a look at gson. It's easy to use, you can find a lot of example of how it works all over the web (official user guide).

Example:

Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("Lokesh");
employee.setLastName("Gupta");
employee.setRoles(Arrays.asList("ADMIN", "MANAGER"));

Gson gson = new Gson();

System.out.println(gson.toJson(employee));

Output:

{"id":1,"firstName":"Lokesh","lastName":"Gupta","roles":["ADMIN","MANAGER"]}

From howtodoinjava.com/'s Google Gson Tutorial : Convert Java Object to / from JSON.

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.