{ "cache_size" : 500, "memory_size" : 450, "test_var1" : "THIS IS A TEST VALUE", "test_var2" : "THIS IS ANOTHER TEST VALUE"}
import com.google.gson.Gson;
import java.io.*;
/*
Json file should resemble the class definition:
{ "memory_size" : 123, "cache_size" : 123 }
*/
/**
* Created by Kyle on 6/7/15.
* Using the Google's Gson library to serialize/deserialize objects
*/
public class Main {
private static final String JSON_FILE = "config.json";
public static void main(String... args)
{
// Read file
File file = new File(JSON_FILE);
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = null;
StringBuilder str = new StringBuilder();
// Grab each line, using StringBuilder for performance
while((line = reader.readLine()) != null)
{
str.append(line);
}
// Create Gson object to convert json to Settings object
Gson gson = new Gson();
Settings settings = gson.fromJson(str.toString(), Settings.class);
System.out.println(settings.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e)
{
}
}
// All fields should map to fields within the json document.
private class Settings
{
public int memory_size;
public int cache_size;
public String test_var1;
public String test_var2;
public Settings(){}
public String toString()
{
return "Memory: " + memory_size + "\nCache: " + cache_size + "\ntest_var1: " + test_var1 + "\ntest_var2: " + test_var2;
}
}
}