Skip to content

Instantly share code, notes, and snippets.

@hugithordarson
Created February 6, 2016 22:17
Show Gist options
  • Save hugithordarson/a697bbd2c8a6f43d015f to your computer and use it in GitHub Desktop.
Save hugithordarson/a697bbd2c8a6f43d015f to your computer and use it in GitHub Desktop.
package strimillinn.xperimental;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JSONExample {
private static final Gson gson = new GsonBuilder().create();
public static void main( String[] args ) {
try {
File f = new File( "test.json" );
String jsonString = new String( Files.readAllBytes( f.toPath() ), "utf-8" );
MyJSONFile objectGraph = gson.fromJson( jsonString, MyJSONFile.class );
System.out.println( objectGraph.companies.get( 0 ).name );
}
catch( IOException e ) {
throw new RuntimeException( "Dude. I'm doing example code, I can't be bothered with handling exceptions." );
}
}
public static class MyJSONFile {
public List<Company> companies;
}
public static class Company {
public String name;
public List<Department> departments;
}
public static class Department {
public String name;
public List<Employee> employees;
}
public static class Employee {
public String name;
public String emailAddress;
public boolean fireAtNextrestructuring;
public Integer howInterestingToTalkToFromOneToTen;
}
}
{
"companies": [
{
"name" : "JubbaCo",
"departments" : [
{
"name" : "Logistics",
"employees" : [
{
"name" : "Hugi"
}
]
}
]
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment