Search code examples
javayamljackson-dataformat-yaml

YAML parsing question for strangely formatted text


I am trying to parse a bit of yaml, and I cannot figure out what construct I need to read it with a YAML parser....I've simplified it here:

name: Test User
age: 30
address:
  /home/joe:
    post:
      summary:  My summary

But no matter what I do, I am getting this....

com.fasterxml.jackson.databind.exc.MismatchedInputException: 
    Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)
 at [Source: (File); line: 5, column: 5] (through reference chain: User["address"]->java.util.LinkedHashMap["/home/joe"])

I can't seem to find another example like this one. I've defined these variable types in my test program:

private String name;
private int age;
private Map<String, String> address;

This works fine if the file looks like:

name: Test User
age: 30
address:
  /home/joe:
  post:
  summary:  My summary

but once I indent those fields the way they are in the actual file, I can't seem to figure out the structure I need to parse it.


Solution

  • Since there is indentation under /home/joe, it's value is an Object, and so the address property would need to be Map<String, Object> (or use a more appropriate sub type, such as a custom Post class with a summary String field) and would have a size of 1 in the given example

    If there is no indentation, then the address Map would have a size of 3