将json对象转为xml进行操作属性

将json对象转为xml进行操作属性

文章目录

前端发送json数据格式

复制代码
{
    "questionContent": {
        "title": "3. Fran正在构建一个取证分析工作站,并正在选择一个取证磁盘控制器将其包含在设置中。 以下哪些是取证磁盘控制器的功能? (选择所有适用的选项。)",
        "choiceImgList": {},
        "choiceList": {
            "A": "A. 防止修改存储设备上的数据",
            "B": "B. 将数据返回给请求设备",
            "C": "C. 将设备报告的错误发送给取证主机",
            "D": "D. 阻止发送到设备的读取命令"
        }
    }
}

写入数据库格式-content字段存储(varchar(2000))

content字段落入库中的格式

复制代码
<QuestionContent>
  <title>Lisa正在试图防止她的网络成为IP欺骗攻击的目标,并防止她的网络成为这些攻击的源头。 以下哪些规则是Lisa应在其网络边界配置的最佳实践?(选择所有适用的选项)
</title>
  <titleImg></titleImg>
  <choiceList>
    <entry>
      <string>A</string>
      <string>阻止具有内部源地址的数据包进入网络</string>
    </entry>
    <entry>
      <string>B</string>
      <string>阻止具有外部源地址的数据包离开网络</string>
    </entry>
    <entry>
      <string>C</string>
      <string>阻止具有公共IP地址的数据包进入网络</string>
    </entry>
    <entry>
      <string>D</string>
      <string> 阻止带有私有IP地址的数据包离开网络</string>
    </entry>
  </choiceList>
  <choiceImgList/>
</QuestionContent>

Question实体类-接口映射对象

复制代码
@XmlRootElement指定一个类为 XML 根元素。JAXB 是一种允许 Java 开发者将 Java 对象映射为 XML 表示形式,以及从 XML 还原为 Java 对象的技术。
Question 类被注解为 XML 根元素。当你使用 JAXB 序列化一个 Question 对象时,它将生成一个以 <Question> 为根元素的 XML 文档

import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Question implements Serializable {

	private String content;
	private QuestionContent questionContent;
	
}

QuestionContent 接收参数对象

复制代码
使用@XStreamAlias("QuestionContent")为类指定别名。例如,为QuestionContent类指定别名,当使用XStream序列化对象时,<QuestionContent类指定别名>将作为根元素,而<title>将作为name字段的元素名。


import com.thoughtworks.xstream.annotations.XStreamAlias;

@XStreamAlias("QuestionContent")
public class QuestionContent {

	@XStreamAlias("title")
	private String title;
	@XStreamAlias("titleImg")
	private String titleImg = "";
	@XStreamAlias("choiceList")
	private LinkedHashMap<String, String> choiceList;
	@XStreamAlias("choiceImgList")
	private LinkedHashMap<String, String> choiceImgList;

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitleImg() {
		return titleImg;
	}

	public void setTitleImg(String titleImg) {
		this.titleImg = titleImg;
	}

	public LinkedHashMap<String, String> getChoiceList() {
		return choiceList;
	}

	public void setChoiceList(LinkedHashMap<String, String> choiceList) {
		this.choiceList = choiceList;
	}

	public LinkedHashMap<String, String> getChoiceImgList() {
		return choiceImgList;
	}

	public void setChoiceImgList(LinkedHashMap<String, String> choiceImgList) {
		this.choiceImgList = choiceImgList;
	}

}

DAO持久层

复制代码
public interface QuestionMapper {

	public void insertQuestion(Question question) throws Exception;
	
	public void addQuestionKnowledgePoint(@Param("questionId") int questionId,
			@Param("pointId") int pointId) throws Exception;
}	

Mapper层

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.extr.persistence.QuestionMapper">

<insert id="addQuestionKnowledgePoint">
		insert into et_question_2_point
		(question_id,point_id)
		values
		(#{questionId},#{pointId})
	</insert>

	<insert id="insertQuestion" parameterType="com.extr.domain.question.Question"
		useGeneratedKeys="true" keyProperty="id">
		insert into et_question
		(name,content,question_type_id,create_time,creator,
		answer,analysis,reference,examing_point,keygetQuestionListword,points)
		values
		(#{name},#{content},#{question_type_id},#{create_time},#{creator},
		#{answer},#{analysis},#{referenceName},#{examingPoint},#{keyword},#{points})
	</insert>
</mapper>	

Service层

java 复制代码
	
@Service("questionService")
public class QuestionServiceImpl implements QuestionService {	

    @Autowired
	private QuestionMapper questionMapper;
    
	@Override
	@Transactional
	public void addQuestion(Question question) {
		// TODO Auto-generated method stub
		try {
			questionMapper.insertQuestion(question);
			for (Integer i : question.getPointList()) {
				questionMapper.addQuestionKnowledgePoint(question.getId(), i);
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}
}
		

Controller控制层接收

复制代码
import com.extr.util.xml.Object2Xml;	
@Controller
public class QuestionController {

	@RequestMapping(value = "/admin/questionAdd", method = RequestMethod.POST)
	public @ResponseBody Message addQuestion(@RequestBody Question question) {
	
		question.setContent(Object2Xml.toXml(question.getQuestionContent()));
		Message message = new Message();
		try {
			questionService.addQuestion(question);
		} catch (Exception e) {
			message.setResult("error");
			log.Info(e.getClass().getName());
			log.info(e);
		}
		return message;
	}
}

xml与对象互转处理

复制代码
package com.extr.util.xml;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class Object2Xml {
	public static String toXml(Object obj){
		XStream xstream=new XStream();
		xstream.processAnnotations(obj.getClass());
		
		return xstream.toXML(obj);
	}
	
	public static <T> T toBean(String xmlStr,Class<T> cls){
		XStream xstream=new XStream(new DomDriver());
		xstream.processAnnotations(cls);
		@SuppressWarnings("unchecked")
		T obj=(T)xstream.fromXML(xmlStr);
		return obj;
	}

pom.xml引入

用于将Java对象序列化为XML,以及从XML反序列化为Java对象。它提供了一种直观的方式来处理Java对象和XML之间的转换,而无需编写大量的映射代码或配置。

复制代码
		<!-- Xstream -->
		<dependency>
			<groupId>com.thoughtworks.xstream</groupId>
			<artifactId>xstream</artifactId>
			<version>1.4.2</version>
		</dependency>

查询功能-xml以json返回页面

java 复制代码
public class QuestionAdapter {
    
	private QuestionContent questionContent;
    
    @GetMapping("/some-endpoint")  
    public @ResponseBody String getQuestionContentAsJson((Question question)) {  
         
        this.questionContent = Object2Xml.toBean(question.getContent(),
                        QuestionContent.class);
        question.setQuestionContent(this.questionContent);
        try {  
            return objectMapper.writeValueAsString(this.questionContent);  
        } catch (Exception e) {  
            // 处理异常并返回适当的错误响应  
        }  
        // 如果没有错误,但您仍然想返回一个默认的或空的JSON,您可以这样做:  
        return question; // 或任何其他您想要的默认JSON  
    }
}    
相关推荐
大学生亨亨22 分钟前
go语言八股文(五)
开发语言·笔记·golang
raoxiaoya23 分钟前
同时安装多个版本的golang
开发语言·后端·golang
此木|西贝1 小时前
【设计模式】享元模式
java·设计模式·享元模式
cloues break.2 小时前
C++进阶----多态
开发语言·c++
我不会编程5552 小时前
Python Cookbook-6.10 保留对被绑定方法的引用且支持垃圾回收
开发语言·python
道剑剑非道2 小时前
QT开发技术【qcustomplot 曲线与鼠标十字功能】
开发语言·qt·计算机外设
李少兄2 小时前
解决Spring Boot多模块自动配置失效问题
java·spring boot·后端
刘婉晴2 小时前
【环境配置】Mac电脑安装运行R语言教程 2025年
开发语言·macos·r语言
Despacito0o2 小时前
C++核心编程:类与对象全面解析
开发语言·c++