0

为什么我这样做时会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));
        }
    }
}
4

1 回答 1

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"}

{}

于 2013-10-19T02:09:33.747 回答