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
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/
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.
If you use gwt as the tag says, then why do you do JSON yourself? GWT has great serialization support.
精彩评论