简体   繁体   中英

gson.toJson(obj) local class

Why does gson.toJson(obj) return null when I do this?

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?

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.

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

{}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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