Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Json String manually

Tags:

java

json

gson

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,

like image 533
user1145874 Avatar asked Jan 03 '14 13:01

user1145874


2 Answers

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);
like image 94
fluminis Avatar answered Sep 23 '22 14:09

fluminis


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.

like image 42
Evgeny Lebedev Avatar answered Sep 26 '22 14:09

Evgeny Lebedev