Last active
July 14, 2017 02:00
-
-
Save keinix/47e91bd7ec77c61adedec0d31ef72060 to your computer and use it in GitHub Desktop.
Assign Json values to class variables or Map with Gson examples.
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
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