Created
March 24, 2010 10:14
-
-
Save esfand/342154 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Json (de)serializer for GWT. | |
// To work with JSON in GWT: | |
public class Customer extends JavaScriptObject { | |
public final native String getFirstName() /*-{ | |
return this.first_name; | |
}-*/; | |
public final native void setFirstName(String value) /*-{ | |
this.first_name = value; | |
}-*/; | |
public final native String getLastName() /*-{ | |
return this.last_name; | |
}-*/; | |
public final native void setLastName(String value) /*-{ | |
this.last_name = value; | |
}-*/; | |
} | |
// Once you have the overlay type defined, it's easy to create a | |
// JavaScript object from JSON and access its properties in Java: | |
public static final native Customer buildCustomer(String json) /*-{ | |
return eval('(' + json + ')'); | |
}-*/; | |
// If you want the JSON representation of the object again, | |
// you can wrap the overlay type in a JSONObject: | |
Customer customer = buildCustomer("{'Bart', 'Simpson'}"); | |
customer.setFirstName("Lisa"); | |
// Displays {"first_name":"Lisa","last_name":"Simpson"} | |
Window.alert(new JSONObject(customer).toString()); | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// It is cheaper and faster to make my beans khow how to convert themselves | |
// to and from json. Like this: | |
public class SmartBean { | |
private String name; | |
public String getName() { return name; } | |
public void setName(String value) { name = value; } | |
public JSONObject toJson() { | |
JSONObject result = new JSONObject(); | |
result.put("name", new JSONString(this.name)); | |
return result; | |
} | |
public void fromJson(JSONObject value) { | |
this.name = value.get("name").isString().stringValue(); | |
} | |
} | |
// JSONxxxx are GWT built-in classes that provide low-level json support. | |
// To convert a JavaScriptObject overlay type into a JSON string? | |
public native String toJSON() /*-{ | |
return this.toString(); | |
}-*/; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment