需求背景:
在接口中,需要对返回的数据进行格式校验,对于不符合要求的返回数据就表示接口数据有变更,对于该接口及时了解到接口参数的变化。所以需要对接口返回的json 字符串进行格式校验。
ps :接口返回参数有两种类型,一个是json 字符,另一种是xml .对应xml格式的数据,按照将xml 改成json 再进行校验。
为了下次使用方便,特将该实现做出utils 以备下次使用
实现如下:
pom.xml 文件
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom2</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>com.github.java-json-tools</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.10</version>
</dependency>
实现如下:
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.xy.onlineteam.schema.core.XmlUtil;
import org.jdom2.JDOMException;
import java.io.IOException;
/**
* Schema校验
*/
public class SchemaValidater {
private final static JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
public static boolean validateForJson(String json, String mainSchema) throws IOException {
JsonNode mainNode = JsonLoader.fromString(mainSchema);
JsonNode instanceNode = JsonLoader.fromString(json);
JsonSchema schema = null;
ProcessingReport processingReport = null;
try {
schema = factory.getJsonSchema(mainNode);
processingReport = schema.validate(instanceNode);
} catch (ProcessingException e) {
e.printStackTrace();
}
return processingReport.isSuccess();
}
/**
*
* @param json 验证的Json
* @param mainSchema 验证的Schema
* @return
* @throws IOException
* @throws JDOMException
*/
public static boolean validateForXml(String json, String mainSchema) throws IOException, JDOMException {
JSONObject jsonObject = XmlUtil.xml2JSON(json);
return validateForJson(jsonObject.toJSONString(), mainSchema);
}
import com.alibaba.fastjson.JSONObject;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
public class XmlUtil {
/**
* xmlString 转换json
* @param xmlStr
* @return
* @throws JDOMException
* @throws IOException
*/
public static JSONObject xml2JSON(String xmlStr) throws JDOMException, IOException {
byte[] xml = xmlStr.getBytes();
return xml2JSON(xml);
}
/**
* xml 转换Json
*
* @param xml
* @return
* @throws JDOMException
* @throws IOException
*/
public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
JSONObject json = new JSONObject();
InputStream is = new ByteArrayInputStream(xml);
SAXBuilder sb = new SAXBuilder();
org.jdom2.Document doc = sb.build(is);
Element root = doc.getRootElement();
json.put(root.getName(), iterateElement(root));
return json;
}
private static JSONObject iterateElement(Element element) {
List node = element.getChildren();
Element et = null;
JSONObject obj = new JSONObject();
List list = null;
for (int i = 0; i < node.size(); i++) {
list = new LinkedList();
et = (Element) node.get(i);
if (et.getTextTrim().equals("")) {
if (et.getChildren().size() == 0)
continue;
if (obj.containsKey(et.getName())) {
list = (List) obj.get(et.getName());
}
list.add(iterateElement(et));
obj.put(et.getName(), list);
} else {
if (obj.containsKey(et.getName())) {
list = (List) obj.get(et.getName());
}
list.add(et.getTextTrim());
obj.put(et.getName(), list);
}
}
return obj;
}
}
测试代码:
jsonschema 测试
public class SchemaValidaterTest {
public static void main(String[] args) {
String scheme = "{\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"name\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"userList\": {\n" +
" \"type\": \"array\",\n" +
" \"items\": {\n" +
" \"type\": \"object\",\n" +
" \"properties\": {\n" +
" \"age\": {\n" +
" \"type\": \"string\"\n" +
" },\n" +
" \"name\": {\n" +
" \"type\": \"string\"\n" +
" }\n" +
" },\n" +
" \"required\": [\n" +
" \"age\",\n" +
" \"name\"\n" +
" ]\n" +
" }\n" +
" }\n" +
" },\n" +
" \"required\": [\n" +
" \"name\",\n" +
" \"userList\"\n" +
" ]\n" +
"}\n";
String json = "{\n" +
" \"name\": \"test\",\n" +
" \"userList\": [\n" +
" {\n" +
" \"age\": \"12\",\n" +
" \"name\": \"hello\"\n" +
" },\n" +
" {\n" +
" \"age\": \"12\"\n" +
" }\n" +
" ]\n" +
"}\n";
try {
boolean validate = SchemaValidater.validateForJson(json, scheme);
System.out.println(validate);
} catch (IOException e) {
e.printStackTrace();
}
}
}
xml测试
import com.alibaba.fastjson.JSONObject;
import com.xy.onlineteam.schema.core.XmlUtil;
import org.jdom2.JDOMException;
import java.io.IOException;
public class XmlUtilTest {
public static void main(String[] args) throws JDOMException, IOException {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><UpdateRecognitionJarRequest><delayend>0</delayend><delaystart>0</delaystart></UpdateRecognitionJarRequest>";
// JSONObject json = XmlUtil.xml2JSON(xml.getBytes());
// System.out.println(json.toJSONString());
JSONObject jsonObject = XmlUtil.xml2JSON(xml);
System.out.println("xml : " + xml);
System.out.println("json : " + jsonObject.toJSONString());
}
}
最后说明:
Schema 校验工具
SchemaValidater 对外提供两个方法
-
SchemaValidater.validateForJson 该方法提供 JSON schema 验证
-
SchemaValidater.validateForXml 该方法提供xml schema 验证。 注意该方法底层是先将xml 转换成json 然后再进行验证。所以入参schema还是Gson格式
Schema 工具网站参考
-
验证Json跟JSON schema网站
https://www.jsonschemavalidator.net/
-
xml转换Json 网站
https://www.sojson.com/json2xml/