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"
            }
        }
    ]
}
arjun
  • 197
  • 1
  • 1
  • 12

1 Answers1

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.

Spare
  • 82
  • 8