Created
March 7, 2019 09:49
-
-
Save thebrightspark/fed81532f9076be16d7d0bf0259af278 to your computer and use it in GitHub Desktop.
Gson Example
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
Item{name=test, id=1234} | |
{ | |
"name": "test", | |
"id": 1234 | |
} | |
Item{name=test, id=1234} |
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
import com.google.common.base.MoreObjects; | |
import com.google.gson.Gson; | |
import com.google.gson.GsonBuilder; | |
public class GsonTest | |
{ | |
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); | |
public static void main(String... args) | |
{ | |
Item item = new Item("test", 1234); | |
System.out.println(item); | |
System.out.println(); | |
String json = GSON.toJson(item); | |
System.out.println(json); | |
System.out.println(); | |
item = GSON.fromJson(json, Item.class); | |
System.out.println(item); | |
} | |
public static class Item | |
{ | |
private String name; | |
private int id; | |
public Item(String name, int id) | |
{ | |
this.name = name; | |
this.id = id; | |
} | |
@Override | |
public String toString() | |
{ | |
return MoreObjects.toStringHelper(this) | |
.add("name", name) | |
.add("id", id) | |
.toString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment