java 对json 格式做参数格式校验

需求背景:

    在接口中,需要对返回的数据进行格式校验,对于不符合要求的返回数据就表示接口数据有变更,对于该接口及时了解到接口参数的变化。所以需要对接口返回的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 对外提供两个方法

  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/
Java是一种面向对象的编程语言,目前在应用程序开发中被广泛使用。校验JSON格式Java中一项非常重要的任务,在开发中经常需要对JSON数据进行格式验证。JSONJavaScript对象表示法的缩写,它是一种轻量级的数据交换格式。 在Java中,我们可以使用标准的JSON库来校验JSON格式。例如,可以使用Jackson、Gson或JSON-lib等库来解析JSON数据并验证其格式是否正确。这些库都提供了丰富的API来校验JSON格式,并且易于使用。 下面是使用Jackson库进行JSON格式校验的示例代码: ```java import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.exc.MismatchedInputException; public class JsonValidator { private static ObjectMapper objectMapper = new ObjectMapper(); public static boolean isValidJson(String jsonStr) { try { JsonNode jsonNode = objectMapper.readTree(jsonStr); return true; } catch (MismatchedInputException e) { return false; } catch (Exception e) { return false; } } } ``` 该代码会将JSON字符串传入isValidJson()方法中,使用Jackson库的readTree()方法来解析JSON数据,并返回解析结果。如果解析失败,则说明JSON格式不正确,方法会返回false。如果解析成功,则说明JSON格式正确,方法返回true。 使用上述代码可以轻松地校验JSON格式。当然,也可以在需要的情况下进行定制化的校验,例如校验JSON键名、键值类型等,以适应各种业务需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dream_bin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值