解析YAML字符串时,标签不能用于缩进

时间:2015-12-14 16:57:45

标签: java yaml yamlbeans

我有byte[]表示UTF-8编码的YAML字符串,我想反序列化它。这是我正在使用的通用方法:

public static <T> T getInstanceFromBinary(final Class<T> clazz, final byte[] binary, final String encoding)
        throws IOException {
    final StringReader stringReader = new StringReader(new String(binary, encoding));
    final String yamlString = stringReader.toString();
    final boolean hasTab = yamlString.contains("\t");
    final YamlReader reader = new YamlReader(stringReader);
    final T clazzInstance = reader.read(clazz);
    reader.close();
    return clazzInstance;
}

我得到了这个例外:

Caused by: com.esotericsoftware.yamlbeans.tokenizer.Tokenizer$TokenizerException: Line 185, column 35: Tabs cannot be used for indentation.
    at com.esotericsoftware.yamlbeans.tokenizer.Tokenizer.fetchMoreTokens(Tokenizer.java:313)
    at com.esotericsoftware.yamlbeans.tokenizer.Tokenizer.peekNextToken(Tokenizer.java:120)
    at com.esotericsoftware.yamlbeans.tokenizer.Tokenizer.peekNextTokenType(Tokenizer.java:125)
    at com.esotericsoftware.yamlbeans.parser.Parser$20.produce(Parser.java:320)
    at com.esotericsoftware.yamlbeans.parser.Parser.getNextEvent(Parser.java:80)
    at com.esotericsoftware.yamlbeans.parser.Parser.peekNextEvent(Parser.java:91)
    at com.esotericsoftware.yamlbeans.YamlReader.readValueInternal(YamlReader.java:270)
    at com.esotericsoftware.yamlbeans.YamlReader.readValue(YamlReader.java:152)
    at com.esotericsoftware.yamlbeans.YamlReader.readValueInternal(YamlReader.java:295)
    ... 38 more

问题是解码后的字符串似乎不包含制表符。这是调试的屏幕截图,确认了这一点:

Debug info

我还检查过YAMLBeans源代码,found where抛出了这个异常,虽然这并没有说明为什么会发生这种情况或如何解决这个问题。

提前感谢任何见解。

1 个答案:

答案 0 :(得分:3)

你在StringReader上调用toString(),它返回Object.toString()提供的神秘而无用的实现。 java.io.StringReader@329dbdbf,即它不会告诉您是否有标签。

相反,您需要在将其传递给StringReader之前检查您使用的原始String,并可能应用.replaceAll("\t", "\\t")