How would I go about returning a valid json response for a null value?

How would I go about returning a valid json response for a null value?

jgouletjgoulet Posts: 26Questions: 2Answers: 1
edited January 2016 in Free community support

I have a Sprng MVC application, and I am using datatables to populate various tables in the app. I am currently working on a page that has several tables, that pull in data at various points throughout the workflow on the page, based on session attributes.

When the page initially loads, one of these tables will have no data, since it relies on a session attribute for the data to be retrieved.

I am attempting to place a conditional statement in that GET method, which essentially states, "if this session attribute exists, build the table using this data." I am not sure what to use as the "else" for this conditional.

At this point, when the page initially loads, I simply get a pop-up message stating that I have given an invalid json response. Right now, I am simply returning "" since I'm not really sure what to use.

Once I have the session attribute, the table loads with all the correct data.

So basically, I'd just like to know if there is a String that I can return in my method in the "else" conditional that will serve as a valid json response.

TO summarize: in my javascript datatables script, I have the parameter,

 "ajax" : "getThisTableData.htm"

Then, in my controller I have,

  value = "/getThisTableData.htm",  method = RequestMethod.GET
            public String getStuff (HttpServletRequest req) throws IOException{
                 if (null != thisSessionAttribute){
                      do JSON stuff;

                      return json;
                 }
                 else {
                      return "";

So that "else" return value is what I am looking to fix.

This question has an accepted answers - jump to answer

Answers

  • jgouletjgoulet Posts: 26Questions: 2Answers: 1
    Answer ✓

    Nevermind! I answered my own question.

    So I am using Gson to build my json data. All I had to do for my "else" conditional was build an empty string, and return that as my json data. So my "else" statement now looks like this:

                    Gson gson = new GsonBuilder().setPrettyPrinting().create();
                    gson = new GsonBuilder().setPrettyPrinting().create();
                    UserJsonObject userJsonObject = new UserJsonObject();
                    String json2 = gson.toJson(userJsonObject);
    
                    return json2;
    
This discussion has been closed.