RichardG
RichardG

Reputation: 455

Gson gson = new Gson().toJson(data) - incompatible types

I've been following a tutorial on turning an array of objects into JSON but I've come across a few errors that I can't find a solution for.

CODE

Line 60 - 64

Gson gson = new Gson().toJson(data);
response.setContentType("application/json"); 
response.setCharacterEncoding("utf-8");
response.getWriter().write(gson);

ERRORS

Line 60

incompatible types
found   : java.lang.String
required: com.google.gson.Gson
            Gson gson = new Gson().toJson(data);

Line 64

cannot find symbol
symbol  : method write(com.google.gson.Gson)
location: class java.io.PrintWriter
            response.getWriter().write(gson);

Does anyone know how to properly do what I'm trying?

Upvotes: 2

Views: 4378

Answers (2)

Hardik Mishra
Hardik Mishra

Reputation: 14887

Use

toJson() – Convert Java object to JSON format

fromJson() – Convert JSON into Java object

Exmaple:

Employee obj = new Employee(); // Your java object
...

Gson gson = new Gson();

// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);

response.getWriter().write(json);

Upvotes: 2

Louis Wasserman
Louis Wasserman

Reputation: 198211

It certainly looks from your error messages that it should be

String gson = new Gson().toJson(data);

which seems to address both of those errors.

Upvotes: 4

Related Questions