1

I have a Java class with two atrributes that I convert to json using this method. I followed this other answer: Return JSONArray instead of JSONObject, Jersey JAX-RS

public String toString(){
    // takes advantage of toString() implementation to format {"a":"b"}
    JsonObject json =  Json.createObjectBuilder()
            .add("sentence", sentence)
            .add( "category", category).build();
    return json.toString();
}

The String I get is encapsulated into an ArrayList of strings, and sent via HTTP (I am using Jersey):

return Response.status(200).entity(response).build();

How ever, the node client is use cannot parse it properly: it gets the array part, accesses the elements perfectly. But not the json keys and values; returns undefined:

jsonRespuesta = JSON.parse(body)[0];
console.log(jsonRespuesta);
console.log("Frase: " +jsonRespuesta.sentence + " ,Categoria: " + jsonRespuesta.category);

Returns:

{"sentence":"hola","category":"2"}
Frase: undefined ,Categoria: undefined

What's failing? If it helps, capturing the packets with wireshark displays the array members as strings

Community
  • 1
  • 1
ledermauss
  • 307
  • 1
  • 2
  • 13

1 Answers1

1

Is your java client encoding the JSON twice? I noticed you are adding json strings to an ArrayList, but you should really be adding objects to the ArrayList and then stringifying the whole thing once.

Try using JSON.parse() again on jsonRepuesta and see if that gets you what you're looking for. Alternatively, log out a typeof jsonRepuesta -- looks like it's still a string.

Also, see here.

Community
  • 1
  • 1
dvlsg
  • 5,378
  • 2
  • 29
  • 34
  • 1
    The key was that: making and ArrayList and aplying the toString to the whole array. The json was encoded twice, indeed. – ledermauss Jul 07 '16 at 15:08