2017-02-19 41 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