Tori
Tori

Reputation: 1356

How to include hierarchy in JSON for Android?

I have this JSON file that I would like to send to a server with POST

{
    "header1" : {
        "message" : {
           "content" : "Hello",
           "type" : "text"
        },
        "header2" : {
           "address" : "[email protected]"
        }
    }
}

This is the code I have for the json pbject JSONObject jsonObject = new JSONObject();

            jsonObject.put("content", "hello");
            jsonObject.put("type", "text");
            jsonObject.put("address", "[email protected]");
            String message = jsonObject.toString();

My question is how do I code the hierarchy: header1, message and header2?

Upvotes: 1

Views: 103

Answers (2)

Ankit Kumar
Ankit Kumar

Reputation: 3723

    JSONObject json = new JSONObject();
    JSONObject messageObject = new JSONObject();
    JSONObject header2Object = new JSONObject();
    try {

        messageObject .put("content", "Hello");
        messageObject .put("type", "text");

        header2Object .put("address", "[email protected]");

        json.put("header1", messageObject.tostring);
        json.put("header2", header2Object.tostring );
    } catch (Exception ignored) {
    }

Try This

Upvotes: 1

Debanik Dawn
Debanik Dawn

Reputation: 799

I think you should do this in a bottom up fashion.

What I mean is first make a JSONObject with the name header2 and put address in it.

Then make the other JSONObject named message, populate it using put and then in turn place it inside another JSONObject named header1.

JSONObject header2 = new JSONObject ();
header2.put("address", "your address");

Then,

JSONObject header1 = new JSONObject ();
header1.put("header2", header2);

And so on...

Upvotes: 0

Related Questions