4
Goal
Create a JSON with the following structure:
{
"auth": {
"user": "rbz",
"token": "abc123"
}
}
Setting
Creating the root structure:
JSONObject JOraiz = new JSONObject();
Creating the values user
and token
:
JSONObject JOauth_u = new JSONObject();
JSONObject JOauth_t = new JSONObject();
JOauth_u.put("user", "rbz");
JOauth_t.put("token", "abc123");
Attempt 1
Using .put()
, the value of JOraiz
is superscript:
JOraiz.put("auth", JOauth_u);
JOraiz.put("auth", JOauth_t);
Exit: {"auth":{"token": "abc123"}}
Attempt 2
Using .acumulate()
, he creates a Array:
JOraiz.accumulate("auth", JOauth_u);
JOraiz.accumulate("auth", JOauth_t);
Exit: {"auth":[{"user": "rbz"},{"token": "abc123"}]}
Doubt
- How do I have 2 properties within the same JSON object?
Very good! It was what I needed to have done in my answer, but you’ve done even better! I believe the topic will help a lot who searches on
JSONObject
!– rbz
@Rbz That’s right, many JSON errors occur because we don’t pay attention to the structure and already come out writing code, and a few minutes to analyze before can save us a lot of time :-)
– hkotsubo
Exactly. If you’re a guy in a hurry, you’re already on the prowl with
JSONArray
, then to treat is using 3 levels without need. Is that my "TOC" does not let me do gambiarra like this! kkk– rbz