2016-04-14 52 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