JsonConverter { @SuppressWarnings("unchecked") public GenericRecord convert(String json) throws IOException { return convert(mapper.readValue(json, Map.class), baseSchema); } JsonConverter(Schema schema); @SuppressWarnings("unchecked") GenericRecord convert(String json);  }
@Test public void testBasicWithMap() throws Exception { JsonConverter jc = new JsonConverter(sr(f1, f2, f3Map)); String json = "{\"field1\": 1729, \"field2\": [true, true, false], \"field3\": {\"key\": \"value\"}}"; GenericRecord r = jc.convert(json); assertEquals(json, r.toString()); }
@Test public void testBasicWithRecord() throws Exception { JsonConverter jc = new JsonConverter(sr(f1, f2, f3Rec)); String json = "{\"field1\": 1729, \"field2\": [true, true, false], \"field3\": {\"key\": \"value\"}}"; GenericRecord r = jc.convert(json); assertEquals(json, r.toString()); }
@Test(expected=IllegalArgumentException.class) public void testMissingRequiredField() throws Exception { JsonConverter jc = new JsonConverter(sr(f1, f2, f3Rec)); String json = "{\"field2\": [true, true, false], \"field3\": {\"key\": \"value\"}}"; jc.convert(json); }
@Test public void testMissingNullableField() throws Exception { Schema optional = Schema.createUnion( ImmutableList.of(Schema.create(Type.NULL), Schema.create(Type.DOUBLE))); Schema.Field f4 = sf("field4", optional); JsonConverter jc = new JsonConverter(sr(f1, f2, f3Rec, f4)); String json = "{\"field1\": 1729, \"field2\": [true, true, false], \"field3\": {\"key\": \"value\"}}"; GenericRecord r = jc.convert(json); String expect = "{\"field1\": 1729, \"field2\": [true, true, false], \"field3\": {\"key\": \"value\"}, \"field4\": null}"; assertEquals(expect, r.toString()); }
@Test public void testMissingNullableArrayField() throws Exception { Schema.Parser parser = new Schema.Parser(); Schema schemaOptionalArray = parser.parse("[\"null\", {\"type\": \"array\", \"items\": \"int\"}]"); Schema.Field f4 = sf("field4", schemaOptionalArray); JsonConverter jc = new JsonConverter(sr(f1, f2, f3Rec, f4)); String json = "{\"field1\": 1729, \"field2\": [true, true, false], \"field3\": {\"key\": \"value\"}}"; GenericRecord r = jc.convert(json); String expect = "{\"field1\": 1729, \"field2\": [true, true, false], \"field3\": {\"key\": \"value\"}, \"field4\": null}"; assertEquals(expect, r.toString()); }