JAVA如何把XML文件转为对象



    C:\Users\Asus\IdeaProjects\ai-annotation-mgr\target\classes/tmp/export/102173377124798465labels
    99512482858795009.jpg
    99512482858795009.jpg
    
        7
    
    
        500
        348
        3
    
    0
    
        脚部
        Unspecified
        0
        0
        0
        
            266
            267
            309
            301
        
    
    
        脚部
        Unspecified
        0
        0
        0
        
            176
            218
            218
            252
        
    

上图为xml的文件内容

对象类

@Data
@ApiModel("导出xml文件响应体")
@XmlRootElement(name = "annotation")
@XmlAccessorType(XmlAccessType.FIELD)
public class ExportXmlDto implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty("文件夹名称")
    private String folder;

    @ApiModelProperty("图片文件名称")
    private String filename;

    @ApiModelProperty("图片文件存储路径")
    private String path;

    @ApiModelProperty("文件来源")
    private List source;

    @ApiModelProperty("图片的尺寸通道信息")
    private List size;

    @ApiModelProperty("是否用于分隔任务 一般为0")
    @XmlElement(name = "segmented")
    private Integer segmented;

    @ApiModelProperty("图片的尺寸通道信息")
    private List object;



}

代码的实现:

 //xml转为ExportXmlDto
    public static Object xmlToObject(File file) {
        StringBuffer buffer = null;
        try {
            FileResource fileResource = new FileResource(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fileResource.getStream(), StandardCharsets.UTF_8));
            buffer = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Object xmlObject = null;
        Reader reader = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(ExportXmlDto.class);
            // xml转为对象的接口 反序列化
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            reader = new StringReader(buffer.toString());
            xmlObject = unmarshaller.unmarshal(reader);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return xmlObject;
    }

你可能感兴趣的:(业务实现,java,xml,servlet)