How to make an object inside a JSON object in Java?

Asked

Viewed 781 times

1

I’m trying to build the following JSON:

{
   "movies":
        {
        "filme":
            [
            {
                "id":1,
                "titulo":"Os Arquivos JSON ",
            },
            {
                "id":2,
                "titulo":"Sexta-feira 13: JSON vive",
            }
            ]
        }
}

I’m wearing the bible org.json. How can I add new elements to my movie array? For example:

{
    "id":3,
    "id":"Tubarão",
}

Code:

package webNavegator;


import org.json.JSONObject;

public class Controller {

        public static void main(String[] args) {

            String str;
            str = "{\"movies\":{\"filme\":[{\"id\":1,\"titulo\":\"Os Arquivos JSON \"},{\"id\":2,\"titulo\":\"Sexta-feira 13: JSON vive\"}]}}";;
            JSONObject movies = new JSONObject(str);  
        }

}
  • without showing your code it is difficult to help

  • OK, I’ll update the post

2 answers

3


It’s not very clear what you want to do.

If you want to create a JSONObject with the 3 movies, add the third movie in the String that you already have:

str = "{\"movies\":{\"filme\":[{\"id\":1,\"titulo\":\"Os Arquivos JSON \"},{\"id\":2,\"titulo\":\"Sexta-feira 13: JSON vive\"},{\"id\":3,\"titulo\":\"Tubarão\"}]}}";
JSONObject obj = new JSONObject(str);

Now if you’ve got one JSONObject created, and wants to manipulate you to add the third movie, the solution is different. But first you need to understand the structure and syntax of a JSON, because it makes it easier to read and manipulate it:

  • What you have is an object, as it is bounded by { }.
    • This object has the key "movies", whose value is another object.
      • This other object has the key "filme", whose value is an array (as it is bounded by [ ])
        • Each element of this array is an object, containing the keys "id" and "titulo"
        • Array elements are separated by comma

Below is the JSON with explanations about its structure:

{  <-- início do objeto
   "movies":  <- chave "movies"
        {  <- valor da chave "movies", é outro objeto
        "filme":  <- chave "filme"
            [  <- valor da chave "filme", é um array
              {  <- primeiro elemento do array, é um objeto
                "id":1,  <- chave "id", valor 1
                "titulo":"Os Arquivos JSON ",  <- chave "titulo" e valor "Os Arquivos JSON "
              },  <- essa vírgula separa os elementos do array
              {  <- segundo elemento do array, é um objeto
                "id":2,  <- chave "id", valor 1
                "titulo":"Sexta-feira 13: JSON vive",  <- chave "titulo" e valor "Sexta-feira 13: JSON vive"
              }
            ]  <- fecha o array
        }  <- fecha o objeto referente à chave "movies"
}  <-- fim do objeto

So if you want to add a new movie to the array, just do the following:

  • create the object that corresponds to the new movie (with "id" equal to 3 and "titulo" like "Jaws")
  • add this object to the array (which is in the key "filme" of the object which, in turn, is in the key "movies")

Something like that:

String str = "{\"movies\":{\"filme\":[{\"id\":1,\"titulo\":\"Os Arquivos JSON \"},{\"id\":2,\"titulo\":\"Sexta-feira 13: JSON vive\"}]}}";
JSONObject obj = new JSONObject(str); // JSONObject original, só com 2 filmes

// cria o objeto do novo filme
JSONObject novoFilme = new JSONObject();
novoFilme.put("id", 3);
novoFilme.put("titulo", "Tubarão");

obj
    // pega a chave "movies", que é outro objeto
    .getJSONObject("movies")
    // pega a chave "filme", que é um array
    .getJSONArray("filme")
    // adiciona o novo filme no array
    .put(novoFilme);

You could also have done so to create the new movie:

JSONObject novoFilme = new JSONObject("{\"id\":3,\"titulo\":\"Tubarão\"}");

But if the object to be created is too large and complex, it might be better to add the keys one by one, making the code clearer and less prone to typos, since it is very easy to get lost in the middle of several pairs of {} and [] when an object gets too big.

Also note that I didn’t call the main object movies. After all, he didn’t is an object movies, he has a key "movies". I just gave a kind of generic name (obj) because I don’t have the whole context (after all, it could have other keys with different information), otherwise it would give a better name.


Finally, something that is not directly related: the structure of this JSON is a little weird.

Why have a key "movies", and then a key "filme", that ultimately leads to the array of movies? That seems pretty redundant (not to mention that "filme" should be plural, since its value is a list of several films), it could be just like this:

{
   "movies":
      [
        {
          "id":1,
          "titulo":"Os Arquivos JSON ",
        },
        {
          "id":2,
          "titulo":"Sexta-feira 13: JSON vive",
        }
      ]
}

Only one key "movies", whose value is the movie array (or change the key name to "filmes", I don’t know).

Of course it depends a lot on the context, but at first there seems to be no need to create an extra level in the structure, as there is no apparent gain in doing so (you just complicated JSON for no reason).

In fact, if you just want a list of movies, you might not even need to be an object. It could simply be an array:

[
  {
    "id":1,
    "titulo":"Os Arquivos JSON ",
  },
  {
    "id":2,
    "titulo":"Sexta-feira 13: JSON vive",
  }
]

In this case, you would manipulate this JSON directly as a JSONArray.

Again, I’m making these suggestions without having the whole context. If it’s a more complex structure and the list of films is just one of the information returned, then it makes sense to have an object (yet, it doesn’t seem to make much sense to have the key "filme" inside "movies").

2

I know that the question itself has already been answered, but something interesting is not trying to reinvent the wheel, that is, using methods, libs and the like to perform the operation you want without the need to spend a whole effort again.. The Google Gson library helps a lot in this area, being very easy to use.. To transform a class into Json format simply declare:

Filme meuFilme = new Filme("nao sei os parametros");
String json = new Gson().toJson(meuFilme); //basta que sua classe Filme implemente Serializable

and to get your class again just:

Filme filme = new Gson().fromJson(json, Filme.class); //json seria seu filme em formato string Json

for arrays enough:

Filme[] filmes = new Gson().fromJson(json,Filme[].class);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.