1

I've created a wrapper class like below (is this necessary? I tried serializing the treemap directly without making any wrapper class and it failed) following the answer provided in a similar thread.

@Root
public class Example {

   @ElementMap(entry="property", value="value", attribute=true, inline=true)
   private TreeMap<String, String> map;

    public Example()
    {
        map = new TreeMap<String, String>() {
            {
                put("testing1", "a");
                put("testing2", "b");
                put("testing3", "c");
            }
        };
    }
}

Then I try to serialize it with the code below:

Serializer serializer = new Persister();
Example example = new Example();
File result = new File("example.xml");
serializer.write(example, result);

The example.xml file is generated, but it is an empty file. Is it because Treemap is not supported by Simple XML? Am I doing something wrong?

5
  • 1
    Which version are you using? I've tried your code and it generated the file successfully. Commented Jan 17, 2014 at 10:49
  • Version 2.7.1. Really? that's good to hear! I'm using this code in Android development not sure if that makes a difference.. Let me clean the project and try again. Commented Jan 17, 2014 at 15:28
  • Yeah, try for yourself on an stand alone java application to check. Are you sure your Android App have the needed permissions to write in that file? Commented Jan 17, 2014 at 15:42
  • I cleaned my project, rebuild everything and it works this time.. I'm not sure why it didn't.. well hopefully someone will find the above example code useful to serialize a treemap because I couldn't find a working example anywhere. Cheers and thanks @EvertonAgner !! Commented Jan 17, 2014 at 16:08
  • You're welcome! Anyways, I've responded to your question on some thoughts about it. Commented Jan 17, 2014 at 16:18

1 Answer 1

0

As per my comment, I've tried your code and it ran with no problems (on a stand-alone java app). So, my thoughts on what was happening would be:

  • Any compilation or classpath issue, which would probably be corrected on project cleanup
  • If you are debugging it on a physical phone, something may have happened on which it didn't let the program write on that file
  • Your app may had any problem with permissions on writing that file

Anyways, here's the generated file:

<example>
   <property string="testing1" value="a"/>
   <property string="testing2" value="b"/>
   <property string="testing3" value="c"/>
</example>
Sign up to request clarification or add additional context in comments.

1 Comment

Yes I was debugging on my phone probably something happened. Cleaning up the project did the trick :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.