Create Json String manually
gson, java, json
Solution
Writing the JSON manually is not a good solution.
It seems that you encode user_auth twice.
Try this instead:
JsonObject user_auth = new JsonObject();
user_auth.addProperty("user_name", username);
user_auth.addProperty("password", password);
JsonObject rest_data = new JsonObject();
rest_data.addProperty("user_auth", user_auth);
rest_data.addProperty("application", APPLICATION_NAME);
Gson gson = new Gson();
String payload = gson.toJson(rest_data);
Problem
I'm trying to create a Json structure manually in Java. In the end, I need the a string representation of my Json object. Since my project already has a dependency to GSON, I wanted to use this. But after several hours of trying and googling, I think, I completely misunderstand something. At the moment, I have the following (non-working) code: ``` JsonObject user_auth = new JsonObject(); user_auth.addProperty("user_name", username); user_auth.addProperty("password", password); JsonObject rest_data = new JsonObject(); Gson gson = new Gson(); rest_data.addProperty("user_auth", gson.toJson(user_auth)); rest_data.addProperty("application", APPLICATION_NAME); String payload = gson.toJson(rest_data); ``` The problem I'm facing is that the "user_auth" element gets escaped quotes (\" instead of " when it is added to the outer element. How can I prevent this? I also tried to use ``` rest_data.addProperty("user_auth", user_auth.toString()); ``` but this did exactely the same. Regards,