2016-04-14 15 views
0

当我尝试放入JSONObject时,出现JSONException。解析Restlet中的表示形式

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

错误日志:

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

注:

当我尝试打印rep.getText(),我得到以下数据:

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

响应的内容类型似乎是'application/x-www-form-urlencoded',然后'application/json' –

回答

1

你代表objec t不是JSON对象。我实际上认为,当你将它传递给JSONObject()时,它只捕获一个奇怪的字符串。我建议将其解析为一个数组:

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")); 
} 
1

你在POST中接收的是HTTP表单编码数据而不是JSON。

Restlet可以和本地处理这些对象,提供Form对象与它们进行交互。而不是new JSONObject(String)尝试new Form(String),例如:

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

我离开其余作为练习读者。

或者您需要调整提交数据的客户端以JSON进行编码,请参阅http://www.json.org/以获取该语法的描述。

仅供参考,核心Restlet库中的Form类是org.restlet.data.Form

+0

'form.getFirstValue(“username”)'给出null。我在Content Body中调用Content Type为“application/json”和json的URL。 –

+0

@MyGod我运行上面的代码行,你输入的字符串是你要输出的'user1'。 Restlet的一件事情可能是调用getText()两次可以第二次给予null对象,因为它不会总是读取流两次。而不是传递来自'getText()'....的结果中的Representation传递。您可能正在发送JSON,但这不是似乎到达的地方,我无法从当前信息中知道可能会将它转换方式。 – Caleryn