0

我非常熟悉在 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?

4

1 回答 1

0

The Schema class has a toString() method that does what you want:

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) );
    }
}

Here's the output:

{
  "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"
  } ]
}
于 2014-06-19T03:39:05.150 回答