首页 > 解决方案 > 如何在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.

标签: jsonjacksongson

解决方案


有点不清楚你的问题到底是什么,但你的例子中的主要问题是你正在将一个 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}


推荐阅读