0

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.

  • Seems like `Map>>` should be the data type of `address`. Or you can create a set of java classes corresponding to that structure. – ernest_k May 13 '21 at 14:54

1 Answers1

0

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

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Thanks, that does work if I put it in my main file. If I make a class to do it with an empty constructor, the variable, and a getter, I still get the same error. I was able to make a class for another one like this that did just have strings, but does using a type like Map require something else in the class? I can use the main file, but I was going to make subclasses for each type. – NCDeveloper May 14 '21 at 18:06
  • It's generally recommended to use specific classes if you have defined fields for each type rather than maps, yes – OneCricketeer May 14 '21 at 18:28
  • What else might need to go in the class? I added the same thing I have in the main file...not sure why the separate class didn't work :( – NCDeveloper May 15 '21 at 21:10
  • I'm not exactly sure what you mean by "main file". Where you define classes (same file or different files) doesn't matter – OneCricketeer May 16 '21 at 12:24
  • As mentioned, if you have defined fields, you should have 4 classes total. You can upload your yaml here to generate that for you https://jsonformatter.org/yaml-to-java – OneCricketeer May 16 '21 at 12:28