如何在Java中编码嵌套的JSONObject?

时间:2019-07-06 06:33:13

标签: java android json httpurlconnection

我必须使用android中的httpurlconnection将参数发送到服务器,在服务器中,我说发布的打印信息和我的参数是我编码的嵌套jsonobject,但是第二个json编码错误,这是什么问题? 这是我的参数:

JSONObject postDataParams = new JSONObject();
postDataParams.put("name", "Manjeet");
postDataParams.put("email", "manjeet@gmail.com");

JSONObject par = new JSONObject();
par.put("class", "a");
par.put("family", "aray");

postDataParams.put("par", par);

我对此进行了编码:

 writer.write(encodeParams(postDataParams));

这是encodeParams函数:

private static String encodeParams(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
 }
 return result.toString();
}

它是服务器中的php:

<?php 

print_r(json_encode($_POST));

?>

及其输出: {“ par”:“ {\” class \“:\” a \“,\” family \“:\” aray \“}”,“ email”:“ manjeet@gmail.com”,“ name”:“ Manjeet”} 但我希望输出是这样的: {“ par”:“ {” class“:” a“,” family“:” aray“}”,“ email”:“ manjeet@gmail.com”,“ name”:“ Manjeet”}

0 个答案:

没有答案