hi, everyone

I am a Java newbie. I have followed a bunch of tutorials and examples from the web but they all failed miserably at teaching me how to properly apply this library: com.google.gson.

First how do I receive properly in the java servlet a json request that has been encoded with JSON.stringify(myRequest) in javascript? I can use String password = request.getParameter("passwordTxt"); but that works only if the requests are not encoded with stringify. So first how do I do that?

I learnt how to send responses by using just:

Gson gson = new Gson();
gson.toJson(myClass);

But I think that this useful only if the content of toJson function is an already made class. I want to create the response dynamically.

All I am trying to create is a simple custom response like this:

Let's say I want my request to look like this:

{test: "myValue"} or like this {test: "myValue", myArr: [1, 5, 10]}

I have the following classes:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.JsonObject;

Do I need to use all of them to achieve what I want? How should I proceed? thank you

it is solved

Just for benefits of community here is sample

{name: "peter_budo", userGroup: ["user", "moderator"]}

For this you would require class something like this

public class User {
    @SerializedName("name")
    private String name;
    @SerializedName("userGroup")
    private List<String> userGroups = new ArrayList<String>();

    public String getName() {
        return name;
    }

    public List<String> getUserGroups() {
        return userGroups;
    }
}

JSON will come over HttpClient or similar as a String. In order to get it converted to Java object you have to first parse string to get JsonObject and after it with help Gson class you can cast it to your class type

private User parseJson(String json) {
    JsonParser parser = new JsonParser();
    JsonObject userJson = parser.parse(json).getAsJsonObject();
    Gson gson = new Gson();
    User user = gson.fromJson(userJson, User.class);
    return user;
}
commented: Upvote for the benefit of Peter ;) +14

also I must add that the only class that is needed to be imported for this to work is

import com.google.gson.Gson;

@thorin sorry you are wrong as you need also JsonParser and JsonObject that are part of this library

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.