Skip to content

LinkedHashMap is serialized as HashMap #1

@GoogleCodeExporter

Description

@GoogleCodeExporter
What steps will reproduce the problem?
1. try to serialize a LinkedHashMap from Servlet to javascript layer.

What is the expected output? What do you see instead?
the order of entries in javascript layer should be the same as the Servlet layer

What version of the product are you using? On what operating system?
Version is 1.3.2; the library is included in a Web Application deployed in 
Glassfish v 2.1

Please provide any additional information below.
The bug seems to be related to re-insertion of LinkedHashMap entries in a plain 
HashMap during serialization. In fact, the method "marshall" of class 
"MapSerializer" during the "while(i.hasNext())" cycle, inserts the entries in 
the JSONObject with the method .put(keyString, json). But JSONObject has a 
inner HashMap, so the order of entries is lost during marshalling.
A possible way to resolve this, is to change "on the fly" the inner HashMap of 
JSONObject with a LinkedHashMap, by setting field.setAccessible(true) just 
before marshalling the map. The solution could be like this:

    class  MapSerializer {

        @Override
        public Object marshall(SerializerState state, Object p, Object o)
                throws MarshallException {
            Map map = (Map) o;
            JSONObject obj = new JSONObject();
            JSONObject mapdata = new JSONObject();

            // the following code has been added to support the
            // LinkedHashMap and the keeping of entry order. :)
            //---------------------------------------------//
            if(o != null && o.getClass() == LinkedHashMap.class) {
                try {
                    Field mapField = JSONObject.class.getDeclaredField("myHashMap");
                    mapField.setAccessible(true);
                    mapField.set(mapdata, new LinkedHashMap());
                    mapField.set(obj, new LinkedHashMap());
                } catch (Exception ex) {
                    throw new MarshallException("Cannot update JSON internal map");
                }
            }

            .....

Original issue reported on code.google.com by pierocan...@gmail.com on 27 Jun 2012 at 7:46

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions