我很難用Java處理下面的JSON,這是從外部Ansible劇本返回的:{"Sample": { "tag_description":"abc","tag_category_id":"def","tag_id":"ghi" }, "Sample1": { "tag_description":"jkl","tag_category_id":"mno","tag_id":"pqr" } }我已經(jīng)能夠使用自定義反序列化器成功解析JSON的一個部分,盡管它僅能獲得第一部分。任何想法都將受到高度贊賞。@JsonComponentpublic class TagSerializer extends JsonDeserializer<Tag> {@Overridepublic Tag deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); JsonFactory factory = mapper.getFactory(); JsonNode treeNode = jsonParser.getCodec().readTree(jsonParser); Iterator<Map.Entry<String, JsonNode>> fields = treeNode.fields(); String name = ""; // collect the tag name Map.Entry<String, JsonNode> entry = fields.next(); name = entry.getKey(); // now that we have the tag name, parse it as a separate JSON object JsonNode node = entry.getValue(); // get the values from the JSON String description = node.get("tag_description").asText(); String category_id = node.get("tag_category_id").asText(); String tag_id = node.get("tag_id").asText(); return new Tag(name, category_id, description, tag_id);}}我從Spring Boot REST API端點調用該方法,而我的“標簽”模型是Spring實體
Java JSON處理
慕碼人8056858
2021-04-05 10:15:41