Java中的JSONMap到字符串失败

nwwlzxa7  于 2023-10-14  发布在  Java
关注(0)|答案(2)|浏览(104)

在java中,我尝试将Map转换为JSON字符串。使用下面的代码

private void sendResponse(Map<String, String> responseMap) throws IOException
{

    PrintStream ps = new PrintStream(clientSocket.getOutputStream());   
    JSONObject json = new JSONObject(responseMap);
    ps.println(json.toString());        

}

可变

json results in {"empty":false}  the map contains valid keyvalue pairs.

Map包含如下值

responseMap.put("response", "ok");
        responseMap.put("versionname", "dummy");
        responseMap.put("versioncode", "dummy");
        responseMap.put("package","dummy"); 
        responseMap.put("deviceid", "unknown");
        responseMap.put("devicename", "dummy"); 
        responseMap.put("synclocation", null);
        responseMap.put("extra", "");

我使用的代码来自https://github.com/douglascrockford/JSON-java
任何想法为什么它不工作?

k7fdbhmy

k7fdbhmy1#

Map to Json,Json to Map?我使用Gson库。是不存在问题的
Map到JSON字符串

Gson gson = new GsonBuilder().setPrettyPrinting().create();
Map<String, String> map = new HashMap<String, String>();
map.put("111", "AAAAA");
map.put("222", "BBBBB");
String mapString = gson.toJson(map);
System.out.println(mapString);

输出

{
  "222": "BBBBB",
  "111": "AAAAA"
}

JSON String to Map

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String mapString  = "{\"222\": \"BBBBB\",\"111\": \"AAAAA\"}";
Map<String, String> map = gson.fromJson(mapString, Map.class);
System.out.println(map.get("111"));

输出

AAAAA
8ehkhllq

8ehkhllq2#

我不建议你用你现在的方式做这件事。我创建了一个示例项目,展示了如何使用Map<String,Object>而不是Map<String,String>来实现。
https://github.com/djangofan/json-serialization-jackson-example/blob/main/src/test/java/com/example/TestObjectsTest.java
在该示例中:

....
  private static final ObjectMapper MAPPER = new ObjectMapper();
  .....
  @Test
  void testDeserialization() {
    Map<String, Object> linkedHashMap = new LinkedHashMap<>();
    linkedHashMap.put("foo", "bar");
    linkedHashMap.put("bar", "foo");

    TestObjects.Bar bar = TestObjects.Bar.builder()
        .id(3)
        .description("bar description")
        .stringBoolean("false")
        .nestedMap(linkedHashMap)
        .build();
    TestObjects.Foo foo = TestObjects.Foo.builder()
        .id(1)
        .description("foo description")
        .primitiveBoolean(false)
        .bar(bar)
        .build();

    String serialized = null;
    try {
      serialized = MAPPER.writeValueAsString(foo);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }

    assertTrue(serialized.contains("foo description"));
    try {
      TestObjects.Foo foo1 = MAPPER.readValue(serialized, TestObjects.Foo.class);
      TestObjects.Bar bar1 = foo1.getBar();

      assertEquals(bar1.id, 3);
    } catch (JsonProcessingException e) {
      throw new RuntimeException(e);
    }

  }

相关问题