如何从 Avro Schema 创建有效的 JSON 示例? [英] How to create a valid JSON example from Avro Schema?

查看:38
本文介绍了如何从 Avro Schema 创建有效的 JSON 示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个相当复杂的 Avro 模式(我无法修改).

Got a fairly complicated Avro schema (which I can not modify).

尝试在 Java 中模拟 JSON 示例:

Trying to mock JSON example in java:

GenericRecord genericRecord = AvroUtil.jsonToGenericRecord(jsonData, avroSchema);

一直失败:

Exception in thread "main" org.apache.avro.AvroTypeException: Expected start-union. Got VALUE_STRING

有没有例如可以为任何给定的 Avro 模式提供 JSON 数据示例的在线工具?(这样才能正确匹配)

Is there e.g. online tool that will provide example of JSON data for any given Avro schema? (so that it can match correctly)

尝试模拟 JSON 数据数小时,但仍然没有成功..

Tried mocking JSON data for hours and still no success..

推荐答案

您可以使用 trevni 依赖和测试范围.这里有一个示例代码

You can create random data using trevni dependency and test scope. Here you have a sample code

import org.apache.avro.Schema;
import org.apache.trevni.avro.RandomData;

import java.util.Iterator;

public class JSONExample {
    public static void main(String [] args){
        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" +
                "}");

        Iterator<Object> it = new RandomData(schema, 1).iterator();
        System.out.println(it.next());
    }
}

输出

{"name": "cjnyvbmetf", "age": -1757126879, "sex": "", "active": false}

maven 依赖

<dependencies>
    <dependency>
        <groupId>org.apache.avro</groupId>
        <artifactId>avro</artifactId>
        <version>1.8.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.avro</groupId>
        <artifactId>trevni-core</artifactId>
        <classifier>tests</classifier>
        <version>1.8.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.avro</groupId>
        <artifactId>trevni-avro</artifactId>
        <classifier>tests</classifier>
        <version>1.8.2</version>
    </dependency>
</dependencies>

这篇关于如何从 Avro Schema 创建有效的 JSON 示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆