json - 如何在java中将字符串映射转换为JSON字符串?
问题描述
我有一个与将字符串映射转换为字符串 json 相关的问题,下面的示例
public class Demo {
public static void main(String[] args) throws JsonProcessingException {
String stringRequest = "{A=12, B=23}";
System.out.println(new Gson().toJson(stringRequest));
}
}
```
OUTPUT: "{A\u003d12, B\u003d23}"
Please you help me how can I map this to json string.
解决方案
有点不清楚你的问题到底是什么,但你的例子中的主要问题是你正在将一个 String 对象序列化为 JSON。这就是为什么你会得到这样的输出,它不是 a 的表示,Map
而是 a 的表示String
。
但是,使用该字符串,您可以轻松创建一个Map
然后可以序列化的字符串。除非您想做一些清洁工作,否则不要说这有任何意义,但无论如何:
// Check first which kind of types are keys & values
// keys are always Strings and here it seems that values can be Integers
Type type = new TypeToken<Map<String, Integer>>(){}.getType();
// Create the actual map from that string
Map<String, Integer> map = getGson().fromJson(stringRequest, type);
// Serialize the map to the console (added pretty printing here)
System.out.println(new Gson().toJson(map));
你可以看到:
{“A”:12,“B”:23}
推荐阅读
- c++ - What does the ampersand do here?
- javascript - How to fix addEventListener in my code? It seems like it's being canceled at any time
- python - Local variable have value '.!toplevel.!calendar.!frame' on VARIABLES section visual studio code when debugging python code
- javascript - My WordPress project on the live server is not enqueuing JS files (404 Error Recieved)
- python - Access a form method from generic.UpdateView in Django
- javascript - Three.js animated color change control
- azure - PARAMETERIS 在 Azure 数据工厂中为不同的源参数化链接服务
- docker - 如何在 Docker 容器中使用 Ruby 编写文件?
- python - 登录时出现问题 - python 请求(可能使用 cookie?)
- python - Randomly selecting rows from a dataframe based on a column value