【问题标题】:JSON to Avro conversion using Java [duplicate]使用 Java 将 JSON 转换为 Avro [重复]
【发布时间】:2015-04-14 11:16:41
【问题描述】:

我想将 JSON 数据转换为 Avro 文件。那么如何通过 Java API/代码来实现呢?

我的示例 JSON 文件是:

[
  {
    "ProductID": "101.0",
    "Id": "1.0",
    "OrderID": "1111.0",
    "Name": "John"
  },
  {
    "ProductID": "102.0",
    "Id": "2.0",
    "OrderID": "2222.0",
    "Name": "Taylor"
  }
]

那么第一件事,我如何从 JSON 文件创建 Avro 模式文件?

其次,创建Avro schema后,如何转换成Avro文件?

【问题讨论】:

    标签: java json avro


    【解决方案1】:

    检查以下代码是否对您有用。

    public <T> T jsonDecodeToAvro(String inputString, Class<T> className,
    Schema schema) {
    
         T returnObject = null;
    
         try {
    
             JsonDecoder jsonDecoder = DecoderFactory.get().jsonDecoder(schema,
    inputString);
    
             SpecificDatumReader<T> reader = new
    SpecificDatumReader<T>(className);
    
             returnObject = reader.read(null, jsonDecoder);
    
         } catch (IOException e) {
    
             e.printStackTrace();
    
         }
    
    
    
         return returnObject;
    }
    

    【讨论】:

    • 嗨,如果我将 avro 模式类型保留为 String,那么我在 jsonDecoder(模式,输入字符串)处遇到错误。因为 json 解码器期望模式的类型是Schema。那么怎么解决呢?
    • 有什么建议或更新吗?
    • 我不确定。如果我发现任何东西,会更新你。
    • new Schema.Parser().parse(jsonString) 会将存储为 Json 字符串的模式转换为 Schema 对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2020-07-13
    • 2020-05-20
    • 2020-10-01
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多