簡體   English   中英

如何根據 Avro 模式驗證 JSON

[英]How do I validate JSON against Avro schema

我有一個來自 API 的 JSON 響應,我想根據現有的 Avro 模式進行驗證(使用名稱和類型進行嚴格驗證)。

響應類型

{"name":"alex","age":23,"sex":"M","active":"true"}

模式具有上述類型和數據類型,我想驗證模式並在失敗時拋出異常。(最好是 JAVA)。

我已經使用命令行閱讀了一個解決方案,但我想以編程方式進行。

提前致謝

這是您可以通過編程方式驗證它的方式。

import org.apache.avro.AvroTypeException;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;

import java.io.*;

public class MainClass {
    public static void main (String [] args) throws Exception {
        Schema schema = new Schema.Parser().parse("{\n" +
                "     \"type\": \"record\",\n" +
                "     \"namespace\": \"com.acme\",\n" +
                "     \"name\": \"Test\",\n" +
                "     \"fields\": [\n" +
                "       { \"name\": \"name\", \"type\": \"string\" },\n" +
                "       { \"name\": \"age\", \"type\": \"int\" },\n" +
                "       { \"name\": \"sex\", \"type\": \"string\" },\n" +
                "       { \"name\": \"active\", \"type\": \"boolean\" }\n" +
                "     ]\n" +
                "}");
        String json = "{\"name\":\"alex\",\"age\":23,\"sex\":\"M\",\"active\":true}";
        System.out.println(validateJson(json, schema));
        String invalidJson = "{\"name\":\"alex\",\"age\":23,\"sex\":\"M\"}"; // missing active field
        System.out.println(validateJson(invalidJson, schema));
    }

    public static boolean validateJson(String json, Schema schema) throws Exception {
        InputStream input = new ByteArrayInputStream(json.getBytes());
        DataInputStream din = new DataInputStream(input);

        try {
            DatumReader reader = new GenericDatumReader(schema);
            Decoder decoder = DecoderFactory.get().jsonDecoder(schema, din);
            reader.read(null, decoder);
            return true;
        } catch (AvroTypeException e) {
            System.out.println(e.getMessage());
            return false;
        }
    }
}

注意:如果您在 Java 項目中並在 json 驗證期間遇到上述錯誤。

在我們的項目中,我們期望一個非常長的 JSON 對象具有多個可選字段,因此很難找到它失敗的地方。

使用SpecificDatumReader/GenericDatumReaders 和其他可能的方法嘗試了不同的方法,但我總是以Expected start-union 結束。 獲得了 VALUE_STRING

我們有一個 SpringBoot 應用程序,我們已經將 avsc 文件轉換為 Java。 因此,我們的想法是,如果我們能夠填充 Class 對象並成功對其進行序列化,則表明接收到的 JSON 是有效的。

所以我們最終使用了一個基本的 ObjectMapper 來填充這個類。 如果您使用 avro 庫將 avsc 文件編譯為 Java,那么它帶有一些默認方法來編碼/解碼類

ObjectMapper mapper = new ObjectMapper();
// DeSerializing the JSON to Avro class, but this doesn't check for Schema restrictions
StatusUpdated obj = mapper.readValue(payload, StatusUpdated.class);
// Encoding the class and serializing to raw format, this step validates based on schema
obj.toByteBuffer();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM