sjain
sjain

Reputation: 23344

Parsing Representation in Restlet

I am getting JSONException when I try to put in JSONObject.

@Post
public String someCode(Representation rep) throws ResourceException{
    try {
        rep.getText();
    } catch (IOException e) {
        LOGGER.error("Error in receiving data from Social", e);
    }   

    try {
        JSONObject json = new JSONObject(rep);
        String username = json.getString("username");
        String password = json.getString("password");
        String firstname = json.getString("firstname");
        String lastname = json.getString("lastname");
        String phone = json.getString("phone");
        String email = json.getString("email");

        LOGGER.info("username: "+username); //JsonException
        LOGGER.info("password: "+password);
        LOGGER.info("firstname: "+firstname);
        LOGGER.info("lastname: "+lastname);
        LOGGER.info("phone: "+phone);
        LOGGER.info("email: "+email);

    } catch (JSONException e) {
        e.printStackTrace();
    } 

    return "200";
}

ERROR LOG:

org.json.JSONException: JSONObject["username"] not found.
    at org.json.JSONObject.get(JSONObject.java:516)
    at org.json.JSONObject.getString(JSONObject.java:687)

NOTE:

When I try to print rep.getText(), I get the following data:

username=user1&password=222222&firstname=Kevin&lastname=Tak&phone=444444444&email=tka%40gmail.com

Upvotes: 0

Views: 858

Answers (2)

Caleryn
Caleryn

Reputation: 1084

What you are Receiving in the POST is HTTP Form encoded data not JSON.

Restlet can and does handle these objects natively providing the Form object to interact with them. rather than new JSONObject(String) try new Form(String), for example:

 String data = rep.getText();
 Form form = new Form(data);
 String username = form.getFirstValue("username");

I leave the remainder as an exercise to the reader.

Alternatively you will need to adjust the client submitting the data to encode it in JSON see http://www.json.org/ for the description of this syntax.

For reference the Form class is org.restlet.data.Form in the core Restlet library.

Upvotes: 1

Vic Seedoubleyew
Vic Seedoubleyew

Reputation: 10526

Your rep object isn't a JSON object. I actually think that when you pass it to JSONObject(), it only captures a weird string. I suggest to parse it into an array :

Map<String, String> query_pairs = new LinkedHashMap<String, String>();
String query = rep.getText();
String[] pairs = query.split("&");
for (String pair : pairs) {
    int idx = pair.indexOf("=");
    query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}

Upvotes: 1

Related Questions