2014-03-18 35 views
1

我的应用使用this GsonRequest实现来执行HTTP请求。 某些请求参数不是简单的字符串键和字符串值,但是某些值也可以是映射。Android - 将嵌套地图转换为JSON字符串

例如:

{ 
    "Key1" : "value", 
    "Key2" : { 
     "Key2.1" : "value", 
     "Key2.2" : "value", 
     "Key2.2" : "value" 
    }, 
    "Key3" : "value" 
} 

的JSON以上参数可以使用HashMap就像这样可以了:

Map<String, String> subMap = new HashMap<String, String>(); 

subMap.put("Key2.1", "value"); 
subMap.put("Key2.2", "value"); 
subMap.put("Key2.3", "value"); 

Map<String, String> map = new HashMap<String, String>(); 
map.put("Key1", "value"); 
map.put("Key2", subMap.toString()); 
map.put("Key3", "value"); 

然后我打电话GsonRequest并通过map

然而,请求时,发送的JSON居然是:

{ 
    "Key1" : "value", 
    "Key2" : "{Key2.1 = value, Key2.2 = value, Key2.2 = value}", <-- This is wrong 
    "Key3" : "value" 
} 

我试图巢地图使用JSONObject,没有成功:

map.put("Key2.2", new JSONObject(subMap).toString()); 

会产生JSON :

... 
"Key2" : "{\"Key2.1\" : \"value\", \"Key2.2\" : \"value\", \"Key2.2\" : \"value\"}", 
... 

这一个看起来更好,如果我能逃脱斜线它会是正确的,但不是。

如何正确嵌套地图并正确获取JSON?

回答

1

想了一会儿,我意识到嵌套Strings是错的,不应该使用。但我正在使用它,因为我的GsonRequest扩展的类Request需要参数的HashMap<String, String>映射。

我所做的是强制通过HashMap<String, Object>地图。我没有预料到它会起作用,但我需要尝试一下。它确实奏效。