当前位置:   article > 正文

java 对json 格式做参数格式校验_jackson参数类型校验

jackson参数类型校验

需求背景:

    在接口中,需要对返回的数据进行格式校验,对于不符合要求的返回数据就表示接口数据有变更,对于该接口及时了解到接口参数的变化。所以需要对接口返回的json 字符串进行格式校验。

ps :接口返回参数有两种类型,一个是json 字符,另一种是xml .对应xml格式的数据,按照将xml 改成json 再进行校验。

    为了下次使用方便,特将该实现做出utils 以备下次使用

实现如下:

pom.xml 文件

  1. <dependency>
  2. <groupId>org.jdom</groupId>
  3. <artifactId>jdom2</artifactId>
  4. <version>2.0.6</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.github.java-json-tools</groupId>
  8. <artifactId>json-schema-validator</artifactId>
  9. <version>2.2.10</version>
  10. </dependency>  

 

实现如下:

  1. import com.alibaba.fastjson.JSONObject;
  2. import com.fasterxml.jackson.databind.JsonNode;
  3. import com.github.fge.jackson.JsonLoader;
  4. import com.github.fge.jsonschema.core.exceptions.ProcessingException;
  5. import com.github.fge.jsonschema.core.report.ProcessingReport;
  6. import com.github.fge.jsonschema.main.JsonSchema;
  7. import com.github.fge.jsonschema.main.JsonSchemaFactory;
  8. import com.xy.onlineteam.schema.core.XmlUtil;
  9. import org.jdom2.JDOMException;
  10. import java.io.IOException;
  11. /**
  12. * Schema校验
  13. */
  14. public class SchemaValidater {
  15.   private final static JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
  16.   public static boolean validateForJson(String json, String mainSchema) throws IOException {
  17.       JsonNode mainNode = JsonLoader.fromString(mainSchema);
  18.       JsonNode instanceNode = JsonLoader.fromString(json);
  19.       JsonSchema schema = null;
  20.       ProcessingReport processingReport = null;
  21.       try {
  22.           schema = factory.getJsonSchema(mainNode);
  23.           processingReport = schema.validate(instanceNode);
  24.       } catch (ProcessingException e) {
  25.           e.printStackTrace();
  26.       }
  27.       return processingReport.isSuccess();
  28.   }
  29.   /**
  30.     *
  31.     * @param json 验证的Json
  32.     * @param mainSchema 验证的Schema
  33.     * @return
  34.     * @throws IOException
  35.     * @throws JDOMException
  36.     */
  37.   public static boolean validateForXml(String json, String mainSchema) throws IOException, JDOMException {
  38.       JSONObject jsonObject = XmlUtil.xml2JSON(json);
  39.       return validateForJson(jsonObject.toJSONString(), mainSchema);
  40.   }
 
  1. import com.alibaba.fastjson.JSONObject;
  2. import org.jdom2.Element;
  3. import org.jdom2.JDOMException;
  4. import org.jdom2.input.SAXBuilder;
  5. import java.io.ByteArrayInputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.util.LinkedList;
  9. import java.util.List;
  10. public class XmlUtil {
  11.   /**
  12.     * xmlString 转换json
  13.     * @param xmlStr
  14.     * @return
  15.     * @throws JDOMException
  16.     * @throws IOException
  17.     */
  18.   public static JSONObject xml2JSON(String xmlStr) throws JDOMException, IOException {
  19.       byte[] xml = xmlStr.getBytes();
  20.       return xml2JSON(xml);
  21.   }
  22.   /**
  23.     * xml 转换Json
  24.     *
  25.     * @param xml
  26.     * @return
  27.     * @throws JDOMException
  28.     * @throws IOException
  29.     */
  30.   public static JSONObject xml2JSON(byte[] xml) throws JDOMException, IOException {
  31.       JSONObject json = new JSONObject();
  32.       InputStream is = new ByteArrayInputStream(xml);
  33.       SAXBuilder sb = new SAXBuilder();
  34.       org.jdom2.Document doc = sb.build(is);
  35.       Element root = doc.getRootElement();
  36.       json.put(root.getName(), iterateElement(root));
  37.       return json;
  38.   }
  39.   private static JSONObject iterateElement(Element element) {
  40.       List node = element.getChildren();
  41.       Element et = null;
  42.       JSONObject obj = new JSONObject();
  43.       List list = null;
  44.       for (int i = 0; i < node.size(); i++) {
  45.           list = new LinkedList();
  46.           et = (Element) node.get(i);
  47.           if (et.getTextTrim().equals("")) {
  48.               if (et.getChildren().size() == 0)
  49.                   continue;
  50.               if (obj.containsKey(et.getName())) {
  51.                   list = (List) obj.get(et.getName());
  52.               }
  53.               list.add(iterateElement(et));
  54.               obj.put(et.getName(), list);
  55.           } else {
  56.               if (obj.containsKey(et.getName())) {
  57.                   list = (List) obj.get(et.getName());
  58.               }
  59.               list.add(et.getTextTrim());
  60.               obj.put(et.getName(), list);
  61.           }
  62.       }
  63.       return obj;
  64.   }
  65. }
 

测试代码:

​jsonschema 测试
  1. public class SchemaValidaterTest {
  2.   public static void main(String[] args) {
  3.       String scheme = "{\n" +
  4.               " \"type\": \"object\",\n" +
  5.               " \"properties\": {\n" +
  6.               "   \"name\": {\n" +
  7.               "     \"type\": \"string\"\n" +
  8.               "   },\n" +
  9.               "   \"userList\": {\n" +
  10.               "     \"type\": \"array\",\n" +
  11.               "     \"items\": {\n" +
  12.               "       \"type\": \"object\",\n" +
  13.               "       \"properties\": {\n" +
  14.               "         \"age\": {\n" +
  15.               "           \"type\": \"string\"\n" +
  16.               "         },\n" +
  17.               "         \"name\": {\n" +
  18.               "           \"type\": \"string\"\n" +
  19.               "         }\n" +
  20.               "       },\n" +
  21.               "       \"required\": [\n" +
  22.               "         \"age\",\n" +
  23.               "         \"name\"\n" +
  24.               "       ]\n" +
  25.               "     }\n" +
  26.               "   }\n" +
  27.               " },\n" +
  28.               " \"required\": [\n" +
  29.               "   \"name\",\n" +
  30.               "   \"userList\"\n" +
  31.               " ]\n" +
  32.               "}\n";
  33.       String json = "{\n" +
  34.               " \"name\": \"test\",\n" +
  35.               " \"userList\": [\n" +
  36.               "   {\n" +
  37.               "     \"age\": \"12\",\n" +
  38.               "     \"name\": \"hello\"\n" +
  39.               "   },\n" +
  40.               "   {\n" +
  41.               "     \"age\": \"12\"\n" +
  42.               "   }\n" +
  43.               " ]\n" +
  44.               "}\n";
  45.       try {
  46.           boolean validate = SchemaValidater.validateForJson(json, scheme);
  47.           System.out.println(validate);
  48.       } catch (IOException e) {
  49.           e.printStackTrace();
  50.       }
  51.   }
  52. }
​xml测试
  1. import com.alibaba.fastjson.JSONObject;
  2. import com.xy.onlineteam.schema.core.XmlUtil;
  3. import org.jdom2.JDOMException;
  4. import java.io.IOException;
  5. public class XmlUtilTest {
  6.   public static void main(String[] args) throws JDOMException, IOException {
  7.       String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><UpdateRecognitionJarRequest><delayend>0</delayend><delaystart>0</delaystart></UpdateRecognitionJarRequest>";
  8. //       JSONObject json = XmlUtil.xml2JSON(xml.getBytes());
  9. //       System.out.println(json.toJSONString());
  10.       JSONObject jsonObject = XmlUtil.xml2JSON(xml);
  11.       System.out.println("xml : " + xml);
  12.       System.out.println("json : " + jsonObject.toJSONString());
  13.   }
  14. }

 

最后说明:

Schema 校验工具

SchemaValidater 对外提供两个方法

  1. SchemaValidater.validateForJson 该方法提供 JSON schema 验证

  2. SchemaValidater.validateForXml 该方法提供xml schema 验证。 注意该方法底层是先将xml 转换成json 然后再进行验证。所以入参schema还是Gson格式

Schema 工具网站参考

  1. 验证Json跟JSON schema网站

https://www.jsonschemavalidator.net/
  1. xml转换Json 网站

https://www.sojson.com/json2xml/
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/829896
推荐阅读
相关标签
  

闽ICP备14008679号