user5420260
user5420260

Reputation: 11

Write and read complex Hashmap to file

I have a hashmap in this format:

Map<String, Map<String, List<String>>> userMap = new HashMap<String, Map<String, List<String>>>();

How can I write the hashmap to a file in a simple way? I want to also be able to read the contents from the file again so I can reuse them in the hashmap later on.

How can I do this?

Upvotes: 1

Views: 91

Answers (2)

hotzst
hotzst

Reputation: 7496

I am using XStream to serialize HashMaps to XML. However you might need some custom converters, if your map implementation is not supported by the converters in XStream. See http://x-stream.github.io/converters.html. HashMap however is among them.

Upvotes: 1

leeor
leeor

Reputation: 17781

There are various approaches:

  • Using java serialization
  • using something like JSON/XML/etc.

JSON has the benefit of being much more concise and human readable than serialization so I would likely prefer it. For JSON, there are lots of great libraries you can use that can accomplish the task very simply. A few recommendations:

  • GSON - google library is really simple to learn and use.
  • Jackson - very powerful, very easy to use as well,has many features and is used in many popular frameworks.

If you did decide to go the Serialization route for any reason, you should be aware than any types you define will need to implement the Serializable marker interface.

Upvotes: 1

Related Questions