Skip to content

Instantly share code, notes, and snippets.

@keinix
Last active July 14, 2017 02:00
Show Gist options
  • Save keinix/47e91bd7ec77c61adedec0d31ef72060 to your computer and use it in GitHub Desktop.
Save keinix/47e91bd7ec77c61adedec0d31ef72060 to your computer and use it in GitHub Desktop.
Assign Json values to class variables or Map with Gson examples.
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
String file;
JsonObject jsonObject;
// used in the map example only
Type type = new TypeToken<Map<String, String>>(){}.getType();
FileReader json = null;
// save values to vars in a class
try {
file = String "path/to/file.json"
FileReader json = new FileReader(file);
jsonObject = gson.fromJson(json, JsonObject.class);
String this.memberVariable = jsonObject.get("jsonKey").getAsString();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//convert json to java map
try {
file = String "path/to/file.json"
json = new FileReader(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Map<String, String> mapName = gson.fromJson(json, type);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment