将Avro生成的对象序列化为JSON时发生JsonMappingException [英] JsonMappingException when serializing avro generated object to json

查看:375
本文介绍了将Avro生成的对象序列化为JSON时发生JsonMappingException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用avro-tools使用以下命令从avsc文件生成Java类:

I used avro-tools to generate java classes from avsc files, using:

java.exe -jar avro-tools-1.7.7.jar compile -string schema myfile.avsc 

然后我尝试通过ObjectMapper将此类对象序列化为json, 但总是得到一个JsonMappingException,上面写着不是枚举"或不是联合". 在我的测试中,我使用生成器或构造器创建了生成的对象. 对于不同类的对象,我得到了这样的例外...

Then I tried to serialize such objects to json by ObjectMapper, but always got a JsonMappingException saying "not an enum" or "not a union". In my test I create the generated object using it's builder or constructor. I got such exceptions for objects of different classes...

示例代码:

ObjectMapper serializer = new ObjectMapper(); // com.fasterxml.jackson.databind
serializer.register(new JtsModule()); // com.bedatadriven.jackson.datatype.jts
...
return serializer.writeValueAsBytes(avroConvertedObject); // => JsonMappingException

我也使用以下命令尝试了许多配置:serializer.configure(...),但仍然失败. 版本:Java 1.8,jackson-datatype-jts 2.3, 杰克逊核心2.6.5,杰克逊数据绑定2.6.5,杰克逊注释2.6.5

I also tried many configurations using: serializer.configure(...) but still failed. Versions: Java 1.8, jackson-datatype-jts 2.3, jackson-core 2.6.5, jackson-databind 2.6.5, jackson-annotations 2.6.5

有什么建议吗? 谢谢!

Any suggestions? Thanks!

推荐答案

如果确实是SCHEMA成员(我们看不到完整的错误消息),则可以将其关闭.我使用mixin来做到这一点,就像这样:

If the SCHEMA member is really the case (we don't see the full error message), then you can switch it off. I use a mixin to do it, like this:

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.avro.Schema;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

public class AvroGenerTests
{
  abstract class IgnoreSchemaProperty
  {
    // You have to use the correct package for JsonIgnore,
    // fasterxml or codehaus
    @JsonIgnore abstract void getSchema();
  }

  @Test
  public void writeJson() throws IOException {
    BookAvro b = BookAvro.newBuilder()
      .setTitle("Wilk stepowy")
      .setAuthor("Herman Hesse")
      .build();
    ObjectMapper om = new ObjectMapper();
    om.enable(SerializationFeature.INDENT_OUTPUT);
    om.addMixIn(BookAvro.class, IgnoreSchemaProperty.class);
    om.writeValue(new File("plik_z_gen.json"), b);
  }
}

这篇关于将Avro生成的对象序列化为JSON时发生JsonMappingException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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