JSONObject with multiple values without using Array

4

Objective

Create a JSON with the following structure:

{
    "auth": {
        "user": "rbz",
        "token": "abc123"
    }
}

Scenario

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 overwritten :

JOraiz.put("auth", JOauth_u);
JOraiz.put("auth", JOauth_t);

Output : {"auth":{"token": "abc123"}}

Attempt 2

Using .acumulate() , it creates an Array :

JOraiz.accumulate("auth", JOauth_u);
JOraiz.accumulate("auth", JOauth_t);

Output : {"auth":[{"user": "rbz"},{"token": "abc123"}]}

Doubt

  • How do I have 2 properties within the same JSON object?
asked by anonymous 29.11.2018 / 11:11

2 answers

3

If you look at the JSON syntax you will see that { and } delimit an object , which is nothing more than a set of key / value pairs.

Now analyzing the JSON you want to create:

{
    "auth": {
        "user": "rbz",
        "token": "abc123"
    }
}

It is an object because it is delimited by { and } . And it contains a auth key whose value is:

{
    "user": "rbz",
    "token": "abc123"
}

That is, the value of the auth key is another object (since it is also delimited by { and } ), which in turn has 2 key / value pairs:

  • key user , with value rbz
  • key token , with value abc123

This makes it easier to know how to create this structure. First I start with the inner object - which has 2 key / value pairs ( user and token ):

// criar o object interno
JSONObject objectInterno = new JSONObject();
// adicionar os 2 pares chave/valor
objectInterno.put("user", "rbz");
objectInterno.put("token", "abc123");

And then we create the main object , adding the internal object as the key value auth :

// criar o object principal
JSONObject principal = new JSONObject();
// adicionar object interno na chave "auth"
principal.put("auth", objectInterno);

System.out.println(principal.toString(4));

So, we have the desired structure:

{"auth": {
    "user": "rbz",
    "token": "abc123"
}}

Your first attempt did not work because put " overwrites the value, if it already exists.

And the second attempt does not work because accumulate " puts the accumulated values into an array . And in addition, you have created two different objects (one for user , and another for token ), which is not necessary since both values are in object .

    
29.11.2018 / 16:27
4

I succeeded, responding:

// Criando objeto JSON raiz
JSONObject JOraiz = new JSONObject();

// Criando objeto JSON auth
JSONObject JOauth = new JSONObject();

// Adicionando propriedades e valores ao objeto JOauth 
JOauth.put("user", "rbz");
JOauth.put("token", "abc123");

// Adicionando propriedades e valores ao objeto JOraiz
JOraiz.put("auth", JOauth);
    
29.11.2018 / 11:25