Gson not recognizing nested JSON object

235
December 10, 2017, at 9:01 PM

I try making the following POST request to my servlet:

$.post('SubmitDashboardInfo/reimbursementRequest',
          {
                startDate       : $('#startDate').val().trim(),
                endDate         : $('#endDate').val().trim(),
                expenseType     : $('#expenseType').val().trim(),
                eventDescription: $('#eventDescription').val().trim(),
                eventCost       : $('#eventCost').val().trim(),
                location        : {
                    streetAddress     : $('#streetAddress').val().trim(),
                    city              : $('#city').val().trim(),
                    stateAbbreviation : $('#state').val().trim(),
                    zipCode           : $('#zipCode').val().trim()
                }/*,
                gradeScale      : $.makeArray($('#gradeScales > tr').map(function() { 
                    var tds = $(this).children('td');
                    return { 
                        letterGrade : $($(tds)[0]).text(),
                        lowerLimit  : $($(tds)[1]).text()
                    };
                }))*/
            }, 
            function(data)
            {
                console.log(data);
            })

, which calls the following service method:

public static boolean validateUserForm(HttpServletRequest req)
{
    // get all the parameters here
    try {
        Type type = new TypeToken<ReimbursementRequest>() {}.getType();
        ReimbursementRequest rr = gson.fromJson(req.getReader(), type);
        System.out.println(rr.toString());

    } catch (JsonSyntaxException e) {
        e.printStackTrace();
        return false;
    } catch (JsonIOException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    catch (NumberFormatException ex)
    {
        ex.printStackTrace();
        return false;
    }
    return true;
}

My ReimbursementRequest POJO looks like this:

package p1.revature.beans;
public class ReimbursementRequest extends Bean {
private int id, requesterID;
private double amount;
private String status;
private int reimbursableEventID;
private ReimbursableEvent reimbursableEvent;

/**
 * Default constructor
 */
public ReimbursementRequest() {
    super();
}
/**
 * Constructor for everything but the id. This is used to insert into the reimbursement request table
 * @param requesterID : the ID of the Employee requesting reimbursement
 * @param amount : the amount requested
 * @param status : the status of the request
 * @param reimbursableEventID : the id of the ReimbursableEvent the requester is trying to have covered
 */
public ReimbursementRequest(int requesterID, double amount, String status, int reimbursableEventID) {
    super();
    this.requesterID = requesterID;
    this.amount = amount;
    this.status = status;
    this.reimbursableEventID = reimbursableEventID;
}
/**
 * Constructor for every field but the reimbursable event id. Used for rendering material client-side
 * @param id
 * @param requesterID
 * @param amount
 * @param status
 * @param reimbursableEvent
 */
public ReimbursementRequest(int id, int requesterID, double amount, String status,
        ReimbursableEvent reimbursableEvent) {
    super();
    this.id = id;
    this.requesterID = requesterID;
    this.amount = amount;
    this.status = status;
    this.reimbursableEvent = reimbursableEvent;
}
/**
 * Constructor for every field. Used for select queries.
 * @param id : the primary key of this request
 * @param requesterID : the ID of the Employee requesting reimbursement
 * @param amount : the amount requested
 * @param status : the status of the request
 * @param reimbursableEventID : the id of the ReimbursableEvent the requester is trying to have covered
 */
public ReimbursementRequest(int id, int requesterID, double amount, String status, int reimbursableEventID) {
    super();
    this.id = id;
    this.requesterID = requesterID;
    this.amount = amount;
    this.status = status;
    this.reimbursableEventID = reimbursableEventID;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public int getRequesterID() {
    return requesterID;
}
public void setRequesterID(int requesterID) {
    this.requesterID = requesterID;
}
public double getAmount() {
    return amount;
}
public void setAmount(double amount) {
    this.amount = amount;
}
public String getStatus() {
    return status;
}
public void setStatus(String status) {
    this.status = status;
}
public int getReimbursableEventID() {
    return reimbursableEventID;
}
public void setReimbursableEventID(int reimbursableEventID) {
    this.reimbursableEventID = reimbursableEventID;
}
public ReimbursableEvent getReimbursableEvent() {
    return reimbursableEvent;
}
public void setReimbursableEvent(ReimbursableEvent reimbursableEvent) {
    this.reimbursableEvent = reimbursableEvent;
}
@Override
public String toString() {
    return "ReimbursementRequest [id=" + id + ", requesterID=" + requesterID + ", amount=" + amount + ", status="
            + status + ", reimbursableEventID=" + reimbursableEventID + ", reimbursableEvent=" + reimbursableEvent
            + "]";
}

}

For some reason, Gson thinks I'm passing it a plain ol string, when I'm actually passing it a JSON string. It returns this error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
    at com.google.gson.Gson.fromJson(Gson.java:888)
    at com.google.gson.Gson.fromJson(Gson.java:853)
    at p1.revature.services.HandleDashboardData.validateUserForm(HandleDashboardData.java:34)
    at p1.revature.servlets.SubmitDashboardInfo.doPost(SubmitDashboardInfo.java:32)

I'm desperately trying to get this project, which is due in 2 days, done. I know this is literally a lot, but please help with this...

Answer 1

You can pass the data as a json object... Stringify.json

I shall try finding an example for you.

Cheers Vicky

Answer 2

After talking over this with a friend, I found that I should be serializing the JavaScript objects with JSON.stringify(myBusinessObj); to send them to the server.

The questions he was asking to me as of why, stumped the hell out of me...

Rent Charter Buses Company
READ ALSO
How to use user-defined Map in Mybatis

How to use user-defined Map in Mybatis

I've create a Class that implements MapThis will convert all the keys to Upper case and prevents duplicates

338
Reference variable pointing to another object

Reference variable pointing to another object

There is an interface called Bank, and it has two implementing classes: ABC and XYZ

195
Identify the best complexity class to which each of the following cost functions belongs:

Identify the best complexity class to which each of the following cost functions belongs:

Am I having everything correctly? I assume the best complexity class would the highest power? or the term with lower power? I am not sure how to choose the best complexity class

198
Call child method in parent&#39;s method? [duplicate]

Call child method in parent's method? [duplicate]

This question already has an answer here:

222