Java-判断一个字符串是否为有效的JSON字符串

在 Java 中判断一个字符串是否为有效的 JSON 字符串,可以使用不同的库来进行验证。常见的库

包括 org.json、com.google.gson 和 com.alibaba.fastjson 等。这里我将展示如何使用

com.alibaba.fastjson 库来实现一个简单的工具类,用于判断给定的字符串是否为有效的 JSON 对

象或数组。

下面是一个示例工具类,名为 JsonValidator,它可以用来检查字符串是否为有效的 JSON:

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;

public class JsonValidator {

    /**
     * 判断给定的字符串是否为有效的 JSON 对象或数组。
     *
     * @param jsonString 要检查的 JSON 字符串
     * @return 如果字符串是有效的 JSON,则返回 true;否则返回 false
     */
    public static boolean isValidJson(String jsonString) {
        if (jsonString == null || jsonString.isEmpty()) {
            return false;
        }
        try {
            // 尝试将字符串解析为 JSON 对象或数组
            JSON.parse(jsonString);
            return true;
        } catch (JSONException e) {
            // 如果解析过程中出现异常,则不是有效的 JSON
            return false;
        }
    }

    public static void main(String[] args) {
        String validJson = "{\"name\":\"John\", \"age\":30}";
        String invalidJson = "This is not a JSON string";

        System.out.println("Valid JSON: " + isValidJson(validJson)); // 应输出 true
        System.out.println("Invalid JSON: " + isValidJson(invalidJson)); // 应输出 false
    }
}

这个工具类使用了 Alibaba 的 FastJSON 库,它提供了 JSON.parse 方法来尝试解析 JSON 字符

串。如果字符串能够被成功解析,则认为它是有效的 JSON;如果抛出了 JSONException 异常,

则认为它不是一个有效的 JSON 字符串。

请注意,为了使用上述代码,你需要在项目中添加 FastJSON 的依赖。如果你使用的是 Maven 或

Gradle,可以相应地添加依赖项。

对于 Maven,可以在 pom.xml 文件中添加如下依赖: 

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.75</version> <!-- 使用最新的版本 -->
</dependency>
package com.lsm.util; import java.text.CharacterIterator; import java.text.StringCharacterIterator; /** * 用于校验一个字符串是否是合法的JSON格式 * @author liShuMin * */ public class JsonValidator { private CharacterIterator it; private char c; private int col; public JsonValidator(){ } /** * 验证一个字符串是否是合法的JSON串 * * @param input 要验证的字符串 * @return true-合法 ,false-非法 */ public boolean validate(String input) { input = input.trim(); boolean ret = valid(input); return ret; } private boolean valid(String input) { if ("".equals(input)) return true; boolean ret = true; it = new StringCharacterIterator(input); c = it.first(); col = 1; if (!value()) { ret = error("value", 1); } else { skipWhiteSpace(); if (c != CharacterIterator.DONE) { ret = error("end", col); } } return ret; } private boolean value() { return literal("true") || literal("false") || literal("null") || string() || number() || object() || array(); } private boolean literal(String text) { CharacterIterator ci = new StringCharacterIterator(text); char t = ci.first(); if (c != t) return false; int start = col; boolean ret = true; for (t = ci.next(); t != CharacterIterator.DONE; t = ci.next()) { if (t != nextCharacter()) { ret = false; break; } } nextCharacter(); if (!ret) error("literal " + text, start); return ret; } private boolean array() { return aggregate('[', ']', false); } private boolean object() { return aggregate('{', '}', true); } private boolean aggregate(char entryCharacter, char exitCharacter, boolean prefix) { if (c != entryCharacter) return false; nextCharacter(); skipWhiteSpace(); if (c == exitCharacter) { nextCharacter(); return true; } for (;;) { if (prefix) { int start = col; if (!string()) return error("string", start); skipWhiteSpace(); if (c != ':') return error("colon", col); nextCharacter(); skipWhiteSpace(); } if (value()) { skipWhiteSpace(); if (c == ',') { nextCharacter(); } else if (c == exitCharacter) { break; } else { return error("comma or " + exitCharacter, col); } } else { return error("value", col); } skipWhiteSpace(); } nextCharacter(); return true; } private boolean number() { if (!Character.isDigit(c) && c != '-') return false; int start = col; if (c == '-') nextCharacter(); if (c == '0') { nextCharacter(); } else if (Character.isDigit(c)) { while (Character.isDigit(c)) nextCharacter(); } else { return error("number", start); } if (c == '.') { nextCharacter(); if (Character.isDigit(c)) { while (Character.isDigit(c)) nextCharacter(); } else { return error("number", start); } } if (c == 'e' || c == 'E') { nextCharacter(); if (c == '+' || c == '-') { nextCharacter(); } if (Character.isDigit(c)) { while (Character.isDigit(c)) nextCharacter(); } else { return error("number", start); } } return true; } private boolean string() { if (c != '"') return false; int start = col; boolean escaped = false; for (nextCharacter(); c != CharacterIterator.DONE; nextCharacter()) { if (!escaped && c == '\\') { escaped = true; } else if (escaped) { if (!escape()) { return false; } escaped = false; } else if (c == '"') { nextCharacter(); return true; } } return error("quoted string", start); } private boolean escape() { int start = col - 1; if (" \\\"/bfnrtu".indexOf(c) < 0) { return error("escape sequence \\\",\\\\,\\/,\\b,\\f,\\n,\\r,\\t or \\uxxxx ", start); } if (c == 'u') { if (!ishex(nextCharacter()) || !ishex(nextCharacter()) || !ishex(nextCharacter()) || !ishex(nextCharacter())) { return error("unicode escape sequence \\uxxxx ", start); } } return true; } private boolean ishex(char d) { return "0123456789abcdefABCDEF".indexOf(c) >= 0; } private char nextCharacter() { c = it.next(); ++col; return c; } private void skipWhiteSpace() { while (Character.isWhitespace(c)) { nextCharacter(); } } private boolean error(String type, int col) { System.out.printf("type: %s, col: %s%s", type, col, System.getProperty("line.separator")); return false; } public static void main(String[] args){ //String jsonStr = "{\"website\":\"oschina.net\"}"; String jsonStr = "{" + " \"ccobjtypeid\": \"1001\"," + " \"fromuser\": \"李四\"," + " \"touser\": \"张三\"," + " \"desc\": \"描述\"," + " \"subject\": \"主题\"," + " \"attach\": \"3245,3456,4345,4553\"," + " \"data\": {" + " \"desc\": \"测试对象\"," + " \"dataid\": \"22\"," + " \"billno\": \"TEST0001\"," + " \"datarelation\":[" + " {" + " \"dataname\": \"关联对象1\"," + " \"data\": [" + " {" + " \"dataid\": \"22\"," + " \"datalineid\": \"1\"," + " \"content1\": \"test1\"," + " \"content2\": \"test2\"" + " }" + " ]" + " }" + " ]" + " }" + " }"; System.out.println(jsonStr+":"+new JsonValidator().validate(jsonStr)); } }
Java 中可以使用一些库来实现 JSON 和 XML 文件的验证,比如: 1. JSON 验证器:可以使用 json-schema-validator 库来验证 JSON 文件是否符合指定的 JSON Schema。以下是一个简单的示例: ```java import com.github.fge.jsonschema.core.exceptions.ProcessingException; import com.github.fge.jsonschema.main.JsonSchema; import com.github.fge.jsonschema.main.JsonSchemaFactory; import com.github.fge.jsonschema.core.report.ProcessingReport; import com.github.fge.jsonschema.core.report.ProcessingMessage; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.net.URL; public class JsonValidator { public static void main(String[] args) throws IOException, ProcessingException { // 读取 JSON 文件和 JSON Schema 文件 String jsonData = "{ \"name\": \"John\", \"age\": 30 }"; String schemaData = "{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } } }"; ObjectMapper mapper = new ObjectMapper(); JsonNode json = mapper.readTree(jsonData); JsonNode schema = mapper.readTree(schemaData); // 创建 JSON Schema 验证器 JsonSchemaFactory factory = JsonSchemaFactory.byDefault(); JsonSchema jsonSchema = factory.getJsonSchema(schema); // 验证 JSON 文件是否符合 JSON Schema ProcessingReport report = jsonSchema.validate(json); // 打印验证结果 if (report.isSuccess()) { System.out.println("JSON 文件符合 JSON Schema!"); } else { for (ProcessingMessage message : report) { System.out.println(message.getMessage()); } } } } ``` 2. XML 验证器:可以使用 javax.xml.validation 包中提供的 API 来验证 XML 文件是否符合指定的 XSD Schema。以下是一个简单的示例: ```java import java.io.File; import javax.xml.XMLConstants; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.xml.sax.SAXException; public class XmlValidator { public static void main(String[] args) { // 读取 XML 文件和 XSD Schema 文件 File xmlFile = new File("example.xml"); File xsdFile = new File("example.xsd"); try { // 创建 XML 验证器 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(xsdFile); Validator validator = schema.newValidator(); // 验证 XML 文件是否符合 XSD Schema validator.validate(new StreamSource(xmlFile)); // 打印验证结果 System.out.println("XML 文件符合 XSD Schema!"); } catch (SAXException e) { System.out.println("XML 文件不符合 XSD Schema:" + e.getMessage()); } catch (IOException e) { System.out.println("无法读取 XML 文件或 XSD Schema 文件:" + e.getMessage()); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ZHOU_VIP

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

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

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

打赏作者

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

抵扣说明:

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

余额充值