Skip to content

Instantly share code, notes, and snippets.

@thebrightspark
Created March 7, 2019 09:49
Show Gist options
  • Save thebrightspark/fed81532f9076be16d7d0bf0259af278 to your computer and use it in GitHub Desktop.
Save thebrightspark/fed81532f9076be16d7d0bf0259af278 to your computer and use it in GitHub Desktop.
Gson Example
Item{name=test, id=1234}
{
"name": "test",
"id": 1234
}
Item{name=test, id=1234}
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