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,
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);
Another way is directly convert POJO into JSON.
1. Create POJO object
i.e. user class:
class User {
@JsonProperty("user_name") // this annotation helps you to specify
// property name in result json
private String userName;
@JsonProperty("first_name")
private String firstName;
// ...
// getters and setters here, hashcode, equals, etc.
}
2. Convert POJO to JSON string
for example:
User user = new User("superlogin", "superpass", ...);
String jsonString = new Gson().toJson(user);
Thats all :)
I think it's more convenient way than build json structure manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With