Search code examples
javayamlyamlbeans

Tabs cannot be used for indentation when parsing YAML string


I have a byte[] that represents a UTF-8-encoded YAML string and I want to deserialize it. Here's the generic method I'm using:

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

and I'm getting this exception:

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

The problem is that the decoded string doesn't seem to contain a tab character. Here's a screenshot from the debug that confirms this:

Debug info

I've also checked YAMLBeans source code, and found where this exception is thrown, although this didn't yield any light about why this is happening or how to solve this issue.

Thanks in advance for any insights.


Solution

  • You are calling toString() on your StringReader which returns the cryptic and rather useless implementation provided by Object.toString(). java.io.StringReader@329dbdbf i.e. it doesn't tell you if you have tabs or not.

    Instead you need to check the original String you used before passing it to StringReader and possibly apply .replaceAll("\t", "\\t")