为什么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));
}
}
}
答案 0 :(得分:0)
我想我仍然不确定你遇到的实际问题是什么......我不能让Gson给我一个空的。
import com.google.gson.Gson;
public class GsonUrlParse {
public static void main( String[] args ) {
Url url = new Url( "foo" );
System.out.println( new Gson().toJson( url ) );
Url nurl = new Url( null );
System.out.println( new Gson().toJson( nurl ) );
}
}
class Url {
String url;
public Url( String url ) {
this.url = url;
}
}
输出:
{ “URL”: “foo” 的}
{}