Created
November 28, 2021 15:47
-
-
Save headwinds/f20c5a4dd9492e54b75397458d41fa9b to your computer and use it in GitHub Desktop.
Java: load json with Gson
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
package services; | |
import com.google.gson.Gson; | |
import java.io.InputStreamReader; | |
import java.io.Reader; | |
import java.util.Map; | |
public class GsonService { | |
public GsonService(){ | |
} | |
public void loadJson(){ | |
try { | |
// create Gson instance | |
Gson gson = new Gson(); | |
// create a reader | |
Reader reader = new InputStreamReader(GsonService.class.getResourceAsStream("/data/cars.json")); | |
// convert JSON file to map | |
Map<?, ?> map = gson.fromJson(reader, Map.class); | |
// print map entries | |
for (Map.Entry<?, ?> entry : map.entrySet()) { | |
System.out.println(entry.getKey() + "=" + entry.getValue()); | |
} | |
// close reader | |
reader.close(); | |
} catch (Exception ex) { | |
ex.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would give credit to this article because I used most of that example only changed 1 line to use
InputStreamReader
instead ofFiles