سؤال

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?

هل كانت مفيدة؟

المحلول 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();

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top