Juan Dela Cruz
Juan Dela Cruz

Reputation: 11

Add key to jsonObject

I want to make something like this:

data{"user":{"age":"23","address":"usa"}}

But I kept on constructing this using JsonObject

{"data":{"user":{"age":"23","address":"usa"}}}

I know that because data is a JsonObject. I just don't know to make it like the one I posted first. Please help

Upvotes: 1

Views: 3202

Answers (2)

Piyush
Piyush

Reputation: 2609

To achieve your desired output try this code:

    try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("age", "23");
            jsonObject.put("address", "usa");

            JSONObject userJson = new JSONObject();
            userJson.put("user", jsonObject);

            String yourFormat = "data" + userJson.toString();
            Log.d("TAG", "Format: " + yourFormat);
        } catch (JSONException e) {
            e.printStackTrace();
        }

Upvotes: 1

Hardik Trivedi
Hardik Trivedi

Reputation: 6092

So first of all you expected output is not a valid JSON object at all. So libraries like GSON, Jackson, and Logansquare, or even default JSON package in android will not help you.

But since your requirement is something like this I would suggest you simply generate

{"user":{"age":"23","address":"usa"}}

Using some of the libraries mentioned above and perform some string manipulation. Write a good method to perform this task.

Upvotes: 0

Related Questions