Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sets don't deserialise to something that equals the original #24

Open
IanRogers opened this issue Jul 29, 2014 · 1 comment
Open

Sets don't deserialise to something that equals the original #24

IanRogers opened this issue Jul 29, 2014 · 1 comment

Comments

@IanRogers
Copy link

The following junit test fails at the last assert with the error:

java.lang.AssertionError: expected: java.util.HashSet<[1]> but was: java.util.HashSet<[1]>

@Test
public void test_Set() throws YamlException {
    Set<Integer> set1 = new HashSet<Integer>(); 
    set1.add(1);
    Set<Integer> set2 = new HashSet<Integer>();
    set2.add(1);
    assertEquals(set1, set2);

    // serialise
    Writer sb = new StringWriter();
    YamlWriter writer = new YamlWriter(sb);        
    writer.write(set1);
    writer.close();
    String yaml = sb.toString();

    // deserialise
    YamlReader reader = new YamlReader(new StringReader(yaml));
    Set<Integer> set3 = (Set<Integer>) reader.read();
    assertEquals(set1, set3);
}

The yaml is:

!java.util.HashSet
- 1
@NathanSweet
Copy link
Member

Java uses erasure for generics. There is no way to know what the generic type of the local variable set is, so you get a string "1" and not an Integer 1. If you want that to work, you could use a class with a field of type Set<Integer>, since the generic type on the field is not erased.

    static public class Meow {
        public Set<Integer> set = new HashSet();
    }

    public void test_Set () throws YamlException {
        Meow meow1 = new Meow();
        meow1.set.add(1);
        Meow meow2 = new Meow();
        meow2.set.add(1);
        assertEquals(meow1.set, meow2.set);

        // serialise
        Writer sb = new StringWriter();
        YamlWriter writer = new YamlWriter(sb);
        writer.write(meow1);
        writer.close();
        String yaml = sb.toString();
        System.out.println(yaml);

        // deserialise
        YamlReader reader = new YamlReader(new StringReader(yaml));
        Meow meow3 = (Meow)reader.read();
        assertEquals(meow1.set, meow3.set);
    }

However, this has not been implemented for YamlBeans. I don't have time at the moment, but you could look at JsonBeans to see how it could be done:
https://github.com/EsotericSoftware/jsonbeans/blob/master/src/com/esotericsoftware/jsonbeans/Json.java#L980

Contributions are welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants