gpt4 book ai didi

java - Android - 将嵌套 map 转换为 JSON 字符串

转载 作者:行者123 更新时间:2023-11-29 21:11:57 30 4
gpt4 key购买 nike

我的应用程序使用 this GsonRequest 发出 HTTP 请求执行。有些请求参数不是简单的字符串键和字符串值,但有些值也可以是映射。

例如:

{
"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 ,但没有成功:

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

将生成 JSON:

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

这个看起来更好,如果我能逃脱斜线,那就对了,但是不行。

如何正确嵌套 map 并正确获取 JSON?

最佳答案

想了想,想到嵌套Strings是错误的,不应使用。但我使用它是因为类 Request ,这是我的GsonRequest扩展,需要 HashMap<String, String>参数映射。

我所做的是强制通过一个HashMap<String, Object> map 。我没想到它会起作用,但我需要试一试。它确实奏效了。

关于java - Android - 将嵌套 map 转换为 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22487288/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com