Clean way to reparse a Map
Suppose I hav开发者_运维知识库e a Map of properties, and I'd like a String representation. toString
buys this in the form {key=value, ...}. I need to send this data over a wire and reparse it into a Map at the other end. What's the best way to do this, given that the data might have a comma in it?
Also, is there any other technique that I'm missing entirely? If I could send over the object over the wire itself, that would be a wonderful. I'd like to avoid RMI, though.
Have you considered just using Java Serialization?
If the keys and values in your Map are pretty simple, you should be golden. ObjectOutputStream and ObjectInputStream will help you out.
It's not incredibly efficient for size and speed, however it's incredibly fast to implement.
EDIT: By pretty simple, yes I mean implement Serializable. But I also mean that the objects are pretty simple objects. If each object is some sort of a graph or tree, then serialization can get a bit more problematic.
If you need human-readability as well as machine-readability, consider using JSON if your map can be serialized with it. There are several libraries that do this, including Google GSON for allowing custom serialization to/from JSON as well.
Or send it as a Properties using its load/save methods.
Since Properties is serializable, using ObjectOutputStream is the cleanest and easiest solution. (Works with all basic Map implementations too but if you happen to have a non-serializable map, you can always create a HashMap with the same content and serialize it instead.)
精彩评论