为什么我这样做时会gson.toJson(obj)
返回?null
public class LoginServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
Gson gson = new Gson();
if (user != null) {
resp.setContentType("application/json");
resp.getWriter().println(gson.toJson(user));
} else {
class Url {
private String url;
Url(String url) {
this.url=url;
}
}
Url obj = new Url(userService.createLoginURL(req.getRequestURI()));
resp.setContentType("application/json");
resp.getWriter().println(gson.toJson(obj));
}
}
}
当我在Url
类之外定义LoginServlet
类时,它会起作用并返回 url 对象的 json 字符串?
class Url {
private String url;
Url(String url) {
this.url=url;
}
}
public class LoginServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
Gson gson = new Gson();
if (user != null) {
resp.setContentType("application/json");
resp.getWriter().println(gson.toJson(user));
} else {
Url obj = new Url(userService.createLoginURL(req.getRequestURI()));
resp.setContentType("application/json");
resp.getWriter().println(gson.toJson(obj));
}
}
}