【问题标题】:Send Nested JSON Object without Escape Character发送没有转义字符的嵌套 JSON 对象
【发布时间】:2017-02-19 02:25:07
【问题描述】:

我正在尝试使用 JSONObjectRequest 将嵌套的 JSONObject 发送到服务器。服务器期望 JSONObject 的格式为:

{  
   "commit":"Sign In",
   "user":{  
      "login":"my username",
      "password":"mypassword"
   }
}

但目前我的程序正在通过以下方式发送 (jsonObject.tostring())

{  
   "commit":"Sign In",
   "user":"   {  
      \"login\”:\”myusername\”,
      \”password\”:\”mypassword\”
   }   ”
}

JSONObjects 由:

final JSONObject loginRequestJSONObject = new JSONObject();
final JSONObject userJSONObject = new JSONObject();
userJSONObject.put("login", "myuser");
userJSONObject.put("password", "mypass");

loginRequestJSONObject.put("user", userJSONObject);
loginRequestJSONObject.put("commit", "Sign In");
Map<String, String> paramsForJSON = new HashMap<String, String>();
paramsForJSON.put("user", userJSONObject.toString().replaceAll("\\\\", "");
paramsForJSON.put("commit", "Sign In");
JSONObject objectToSend =  new JSONObject(paramsForJSON);

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, objectToSend,...)

如何发送上述表单中的 JSONObject?

【问题讨论】:

  • 您使用的是哪台服务器?喜欢 .net 还是 php ?
  • 它正在使用 ruby​​ on rails
  • @BabulPatel 服务器的相关性是什么?
  • 使用 Gson 从类中创建 Json 字符串。

标签: java android json android-volley


【解决方案1】:

这是你的错误:

paramsForJSON.put("user", userJSONObject.toString().replaceAll("\\\\", ""));

你已经把用户变成了String,你不需要这样做:

loginRequestJSONObject.put("user", userJSONObject);

虽然你已经这样做了,但实际上你已经得到了正确的行,这就是你所需要的:

final JSONObject loginRequestJSONObject = new JSONObject();
final JSONObject userJSONObject = new JSONObject();
userJSONObject.put("login", "myuser");
userJSONObject.put("password", "mypass");

loginRequestJSONObject.put("user", userJSONObject);
loginRequestJSONObject.put("commit", "Sign In");

JSONObject objectToSend = loginRequestJSONObject;

【讨论】:

  • 那么我是否应该将 paramsForJSON 映射更改为 Map,并将其交给 JsonObjectRequest?
  • 你知道我刚刚注意到你已经有一些正确的线,不需要地图。
  • A JSONObject 已经是一张有效的地图,这就是为什么如果你有一张地图就可以很容易地创建一张地图。所以跳过中间人,直接使用JSONObjects。
  • 我也建议你看看Gson。我个人使用这个而不是JSONObject
猜你喜欢
  • 2020-03-07
  • 2017-06-23
  • 2019-12-26
  • 2014-12-29
  • 1970-01-01
  • 2021-02-05
  • 1970-01-01
  • 2019-03-15
  • 2023-01-16
相关资源
最近更新 更多