应该很简单,但是我找了一个小时还是找不到。
我需要得到一个JSON字符串,例如,{"k1":v1,"k2":v2},解析为JsonNode。
JsonFactory factory = new JsonFactory();
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = jp.readValueAsTree();
给了
java.lang.IllegalStateException:没有为解析器定义的ObjectCodec,不能将JSON反序列化为JsonNode树
新方法解决老问题。
一个从java 9+工作的解决方案
ObjectNode agencyNode = new ObjectMapper().valueToTree(Map.of("key", "value"));
对于复杂的对象更易于阅读和维护。Ej
Map<String, Object> agencyMap = Map.of(
"name", "Agencia Prueba",
"phone1", "1198788373",
"address", "Larrea 45 e/ calligaris y paris",
"number", 267,
"enable", true,
"location", Map.of("id", 54),
"responsible", Set.of(Map.of("id", 405)),
"sellers", List.of(Map.of("id", 605))
);
ObjectNode agencyNode = new ObjectMapper().valueToTree(agencyMap);
新方法解决老问题。
一个从java 9+工作的解决方案
ObjectNode agencyNode = new ObjectMapper().valueToTree(Map.of("key", "value"));
对于复杂的对象更易于阅读和维护。Ej
Map<String, Object> agencyMap = Map.of(
"name", "Agencia Prueba",
"phone1", "1198788373",
"address", "Larrea 45 e/ calligaris y paris",
"number", 267,
"enable", true,
"location", Map.of("id", 54),
"responsible", Set.of(Map.of("id", 405)),
"sellers", List.of(Map.of("id", 605))
);
ObjectNode agencyNode = new ObjectMapper().valueToTree(agencyMap);