【问题标题】:How to convert string Map to JSON string in java?如何在java中将字符串映射转换为JSON字符串?
【发布时间】:2020-10-26 04:32:09
【问题描述】:

我有一个与将字符串映射转换为字符串 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.

【问题讨论】:

    标签: json jackson gson


    【解决方案1】:

    有点不清楚您的问题到底是什么,但您的示例中的主要问题是您正在将 String 对象序列化为 JSON。这就是为什么你会得到这样的输出,它不是 Map 的呈现,而是 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 }

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 2015-07-06
      • 2023-03-17
      • 2019-06-14
      • 2021-05-10
      • 2021-09-23
      • 2017-01-16
      • 2013-01-18
      • 1970-01-01
      相关资源
      最近更新 更多