Java JSON处理

我很难用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"

    }

 }

我已经能够使用自定义反序列化器成功解析JSON的一个部分,尽管它仅能获得第一部分。任何想法都将受到高度赞赏。


@JsonComponent

public class TagSerializer extends JsonDeserializer<Tag> {




@Override

public 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实体


慕码人8056858
浏览 122回答 2
2回答

鸿蒙传说

如果您使用的是Spring MVC,请在引用时考虑明确声明所需的类型,@RequestBody然后让框架为您完成工作@PostMapping(value="/store", consumes = APPLICATION_JSON_VALUE)public void tagJson(@RequestBody Map<String, Tag> json) {&nbsp; // Do not mess with ObjectMapper here, Spring will do the thing for you}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java