JSON validation with more than one object

Asked

Viewed 504 times

3

I need to send a JSON from a String. When reading a series as below, it works perfectly:

json = {"resultado":" resultado 111","peso":98,"sinal":"-44","nome":"divergencia ativos","quantidade":12}

But when there is more than one series, as below, gives JSON error not valid:

{
    "resultado":" resultado 111",
    "peso":98,
    "sinal":"-44",
    "nome":"divergencia ativos",
    "quantidade":12
}, 
{
    "resultado":" resultado   222",
    "peso":99,
    "sinal":"45",
    "nome":"divergencia geral",
    "quantidade":5
}

How I’m using:

JsonParser parser = new JsonParser();

JsonElement jsonTree = parser.parse(json.toString());
if (jsonTree.isJsonObject()) {
    JsonObject jsonObject = jsonTree.getAsJsonObject();

    object.put("nome", jsonObject.get("nome").getAsString());
    object.put("peso", jsonObject.get("peso").getAsDouble());
    object.put("quantidade", jsonObject.get("quantidade").getAsDouble());
    object.put("sinal", jsonObject.get("sinal").getAsString());
    object.put("resultado", jsonObject.get("resultado").getAsString());
    listaObject.add(object);
}
  • 1

    I don’t know much about Java but its json is an array. Maybe something like JSONArray arr = obj.getJSONArray("nomeCampo"); help you!

  • JSON with two objects at the top is not valid. Either you put the two in an array or another object. The top has to be a single object or array.

  • @Marcelovismari In fact it is almost an array, lacked to be all between [ ] - see [my reply] below :-)

3 answers

3


Gives invalid JSON error because JSON is actually invalid. According to syntax of a JSON, This is an object:

{
    "resultado":" resultado 111",
    "peso":98,
    "sinal":"-44",
    "nome":"divergencia ativos",
    "quantidade":12
}

It is bounded by { }, which means that after the }, it closes. If you put another object just after it, whether separated by comma or not (like your JSON, for example), then you have 2 "loose" objects, and that is invalid.

If you want to have multiple elements in the same structure, an option would be to use an array. And according to JSON syntax, an array must be delimited by [ ], and the elements separated by a comma. If your JSON looked like this, for example:

[
  {
    "resultado":" resultado 111",
    "peso":98,
    "sinal":"-44",
    "nome":"divergencia ativos",
    "quantidade":12
  }, 
  {
    "resultado":" resultado   222",
    "peso":99,
    "sinal":"45",
    "nome":"divergencia geral",
    "quantidade":5
  }
]

Then it would be valid as it is now an array (it is bounded by [ ]) containing two elements (the two objects), separated by comma. Of course this is only an option, the ideal shape will depend on each case.


So how to fix?

The first option is correct the problem at source. If the data should be a JSON, then whoever generates this data should generate a valid, "simple" JSON like this.

Another option - less specified, but if it is not possible to change the source data, "do what" - is to try to bypass invalid JSON by making it valid.

Since invalid JSON has 2 comma-separated objects, just put everything in between [ ] for it to become an array (by the classes and methods, I am assuming that you are using the Gson):

JsonParser parser = new JsonParser();
// colocar entre "[" e "]" para virar um array
JsonElement jsonTree = parser.parse("[ " + json.toString() + " ]");
if (jsonTree.isJsonArray()) {
    JsonArray array = jsonTree.getAsJsonArray();
    for (JsonElement element : array) { // percorre os elementos do array
        if (element.isJsonObject()) {
            JsonObject jsonObject = element.getAsJsonObject();

            object.put("nome", jsonObject.get("nome").getAsString());
            object.put("peso", jsonObject.get("peso").getAsDouble());
            object.put("quantidade", jsonObject.get("quantidade").getAsDouble());
            object.put("sinal", jsonObject.get("sinal").getAsString());
            object.put("resultado", jsonObject.get("resultado").getAsString());
            listaObject.add(object);
        }
    }
}

This works even when there is only one object, because in this case an array with only one element will be generated, and the code works the same way.

But again I reiterate that this solution is a "patch", and that the ideal is that the generated data is already a valid JSON, so that you do not need to be tidying up manually, which depending on the case can be very prone to errors.


I just don’t understand why you’re creating another object the same (with the same keys and values as the jsonObject obtained). But as it was not clear what are object and listaObject, I leave the above code only as reference.

  • Thanks a lot. I followed your tips and managed to solve. Hug.

-2

Your JSON with 2 objects is an array, so you should use the JsonArray, go through the array and then use the JsonObject.

-2

JsonArray value = Json.createArrayBuilder()
     .add(Json.createObjectBuilder()
         .add("resultado", " resultado 111")
         .add("peso", 98)
         .add("sinal", "-44")
         .add("nome", "divergencia ativos")
         .add("quantidade", 12))
     .add(Json.createObjectBuilder()
         .add("resultado", " resultado 222")
         .add("peso", 99)
         .add("sinal", "45")
         .add("nome", "divergencia geral")
         .add("quantidade", 5))
     .build();

Browser other questions tagged

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