2017-02-19 42 views
4

我试图发送一个嵌套的JSONObject到使用JSONObjectRequest的服务器。服务器的形式期待一个JSONObject:发送无跳转字符的嵌套JSON对象

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,...) 

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

,但目前我的计划是通过以下(jsonObject.tostring()

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

的一个JSONObjects发送被由我怎样才能发送上述形式的JSONObject?

+0

你正在使用哪台服务器?像.net或PHP? –

+0

它使用轨道上的红宝石 –

+0

@BabulPatel服务器的相关性是什么? – weston

回答

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; 
+0

所以我应该将paramsForJSON映射更改为Map ,并将其提供给JsonObjectRequest? –

+0

你知道我刚刚注意到你已经有了一些正确的线条,地图是不需要的。 – weston

+0

'JSONObject'已经是一个有效的地图,这就是为什么如果你有地图就很容易创建一个。因此,跳过中间人,并使用'JSONObject'工作。 – weston