简体   繁体   English

gson.toJson(obj)本地类

[英]gson.toJson(obj) local class

Why does gson.toJson(obj) return null when I do this? 为什么我这样做时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));
        }
    }
}

When I define the Url class outside the LoginServlet class it works and returns a json string of the url object? 当我在LoginServlet类之外定义Url类时,它可以工作并返回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));
        }
    }
}

I guess I'm still not sure what the actual problem you're having is...I can't get Gson to give me a null. 我想我仍然不确定您遇到的实际问题是什么...我无法让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;
    }
}

Output: 输出:

{"url":"foo"} {“ url”:“ foo”}

{} {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM