JSON格式的Avro Pair架构

时间:2013-09-09 21:27:00

标签: json avro

我非常熟悉用Java创建Avro对模式。例如,

static final String RECORD_STRING = 
     "{\n" + 
     "   \"type\": \"record\",\n" +
     "   \"name\": \"exampleRecord1\",\n" + 
     "   \"fields\": [\n" + 
     "   {\"name\": \"id\", \"type\": \"string\"}\n" +  
     "]\n" + 
     "}";
static{
    final Schema.Parser parser = new Schema.Parser();
    Schema KEY_SCHEMA = parser.parse(RECORD_STRING);
    Schema VALUE_SCHEMA = Schema.create(Schema.Type(STRING)) ;
    Schema PAIR_SCHEMA = Pair.getPairSchema(KEY_SCHEMA, VALUE_SCHEMA);
}

如何在不使用任何Java的情况下将此Pair Schema直接编写为文件中的JSON?

1 个答案:

答案 0 :(得分:0)

Schema类有toString()方法可以执行您想要的操作:

import org.apache.avro.Schema;
import org.apache.avro.mapred.Pair;

public class Test
{
    static final Schema PAIR_SCHEMA;
    static final String RECORD_STRING =
            "{\n" +
            "   \"type\": \"record\",\n" +
            "   \"name\": \"exampleRecord1\",\n" +
            "   \"fields\": [\n" +
            "   {\"name\": \"id\", \"type\": \"string\"}\n" +
            "]\n" +
            "}";

    static
    {
        final Schema.Parser parser = new Schema.Parser();
        Schema KEY_SCHEMA = parser.parse( RECORD_STRING );
        Schema VALUE_SCHEMA = Schema.create( Schema.Type.STRING );
        PAIR_SCHEMA = Pair.getPairSchema( KEY_SCHEMA, VALUE_SCHEMA );
    }

    public static void main( String[] args )
    {
        System.out.println( PAIR_SCHEMA.toString(true) );
    }
}

这是输出:

{
  "type" : "record",
  "name" : "Pair",
  "namespace" : "org.apache.avro.mapred",
  "fields" : [ {
    "name" : "key",
    "type" : {
      "type" : "record",
      "name" : "exampleRecord1",
      "namespace" : "",
      "fields" : [ {
        "name" : "id",
        "type" : "string"
      } ]
    },
    "doc" : ""
  }, {
    "name" : "value",
    "type" : "string",
    "doc" : "",
    "order" : "ignore"
  } ]
}