Sachin
Sachin

Reputation: 103

Deseralize a JSON ( containing HashMap ) returned from Server

I am using gwt client . I need to parse/de-serialize a JSON ( contains Map ) returned from the server. Sample JSON :-

APPLICATIONSMAP: {

*
  -
  0: {
      o name: "App 1"
      o id: 0
  }
*
  -
  1: {
      o name: "App 2"
      o id: 1
  }
*
  -
  2: {
      o name: "App 3"
      o id: 2
  }

How do I de-serialize the json back to Java HashMap ?

Thanks, Sachin

Upvotes: 2

Views: 695

Answers (3)

Chris Lercher
Chris Lercher

Reputation: 37778

You could try JavaScript Overlay Types, e.g. like this:

public class OverlayExample implements EntryPoint {

    public static final class MyJsMap extends JavaScriptObject {

        protected MyJsMap() {}

        public native Object get(Object key) /*-{
            return this[key];
        }-*/;

        public native void put(Object key, Object val) /*-{
            this[key] = val;
        }-*/;
    }

    public void onModuleLoad() {

        final String text = "[{ 1 : 'x', 2 : 'y' }]";
        final MyJsMap map = asJsMap(text);
        System.out.println(map.get("1"));
    }

    private static native MyJsMap asJsMap(final String str) /*-{
        return eval(str)[0];
    }-*/;
}

Ok, it's not exactly a java.util.Map, but if you need that, you could improve MyJsMap to implement the java.util.Map interface.

Or - if you need a real java.util.HashMap - you could iterate over all values and copy them to a HashMap. In the latter case, it's probably easier to use GSON, as recommended by @The Elite Gentleman.

Upvotes: 1

Alexis Dufrenoy
Alexis Dufrenoy

Reputation: 11946

I'm not sure what you're trying to do is the right way to do things, but if you really want to deserialize from a JSON, you could use Jackson:

http://jackson.codehaus.org/

Upvotes: 1

rapadura
rapadura

Reputation: 5300

If you use gwt as the tag says, then why do you do JSON yourself? GWT has great serialization support.

Upvotes: 0

Related Questions