user13920392
user13920392

Reputation:

Passing json as a String

For a Json body like

{
    "firstName": "hello",
    "lastName": "abc"
}

I am writing as

JSONObject body = new JSONObject();

    
body.put("firstName", "hello");
body.put("lastName", "abc");

and then converting body to string to pass it as string parameter

How can I write the same for body with response like

{
    "class": {
        "firstName": "hello",
        "lastName": "abc"
    }
}

I need to convert json to string afterwards

Upvotes: 1

Views: 372

Answers (2)

Tushar Jajodia
Tushar Jajodia

Reputation: 451

I think this should do the trick

    JSONObject innerBody = new JSONObject();
    innerBody.put("firstName", "hello");
    innerBody.put("lastName", "abc");

    JSONObject outerBody = new JSONObject();
    outerBody.put("class",innerBody);

Upvotes: 1

SoT
SoT

Reputation: 1246

Create a class:

public class DataSource {
    private String firstName;
    private String lastName;
    //Constructor, getter, setter
}

And then:

JSONObject body = new JSONObject();
DataSource data = new DataSource();
data.setFirstName("bla");
data.setLastName("bla bla");
body.put("class", data );

Upvotes: 0

Related Questions