gpt4 book ai didi

java - 解析 ReSTLet 中的表示

转载 作者:行者123 更新时间:2023-12-02 03:43:06 25 4
gpt4 key购买 nike

当我尝试放入 JSONObject 时,出现 JSONException。

@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

最佳答案

您的代表对象不是 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"));
}

关于java - 解析 ReSTLet 中的表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36627758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com