How to manipulate a Json Object before returning to the API

Asked

Viewed 135 times

0

Hello

I have this method in my controller:

@GetMapping(value="/{id}/perfil", produces = MediaType.APPLICATION_JSON_VALUE)
public String carregarPerfilUsuario(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {
     
    obj.put("usuario", ur.findWhereId(id));
    obj.put("postagem", pr.findAllWhereUserId(id));
    
    return gson.toJson(obj);

}

I’m using gson to turn an object into json and JsonOBJECT to create an obj that will be returned at the end:

private static final Gson gson = new Gson();
private static final JSONObject obj = new JSONObject();

however do not know why while converting my data it inserts unwanted attributes into my api:

inserir a descrição da imagem aqui

Map and Myarraylist, I wish I didn’t see those attributes when I convert, like I do?

The result I’m looking for is similar to the image, I just wish I didn’t have these attributes I commented in bold in the question.

  • See if using GSON’s own Jsonobject instead of Jsonobject solves your problem.

  • You’re using the right class (JsonObject)? I tried to reproduce here but I couldn’t find the method put in that class :(

1 answer

0

Hello,

The methods you are using suggest that you have a Map (put method) and an Arraylist (findAll method), hence your map and your myArrayList.

The correct thing to do is to have a POJO that represents the object to be returned by your API, and populate it with user data and posting.

For example:

public class PostagemDTO {

   private Usuario usuario;
   private List<Postagem> postagens;

   // getters e setters

}

So your API will return the desired result.

I hope it helps!

  • Hi Tomaz! Welcome to Stackoverflow in English. I agree with his point of view regarding building a class to serve as a return to the method, rather than String, but that was not his question. It questions the functioning of GSON and its classes. Again, I agree with you about the overall implementation. Even, you can use this as a complement to an answer that answers the exact question! :)

  • Hi, I don’t think I made myself clear, so... The result he is looking for does not need the internal classes of GSON, just create and popular the POJO as I showed, and use the method. toJson But of course Spring does it alone if he returns the POJO direct in control yes. Thanks!

Browser other questions tagged

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