Question

I'm trying to access an API from my java code. The API only accepts data in the form of a JSON object, but I'm having trouble building a JsonObject representation.

What I want to do is use createObjectBuilder() to create a JsonObject formatted as follows:

{
    "user1234@gmail.com": {
        "username" : "user1234@gmail.com",
        "password" : "password1",
        "service" : [ "yourkit" ]
    }
}

I tried this:

JSONObject jsonObject = (JSONObject)Json.createObjectBuilder()
                            .add(
                                username,
                                Json.createObjectBuilder()
                                    .add("username", username)
                                    .add("password", password)
                                    .add("service", service)
                            ).build();

p.setEntity(new StringEntity(jsonObject.toString(), "UTF-8")); 
HttpResponse r = c.execute(p);

But it doesn't send the correct request to the API.

Can someone please help me?

Was it helpful?

Solution 2

You are missing an array for service attribute:

JSONObject jsonObject = (JSONObject)Json.createObjectBuilder()
                        .add(
                            username,
                            Json.createObjectBuilder()
                                .add("username", username)
                                .add("password", password)
                                .add("service",
                                    Json.createArrayBuilder()
                                      .add(service)
                                )
                        ).build();

OTHER TIPS

To achive the format you want the variable service has to be array of strings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top