Skip to content

Instantly share code, notes, and snippets.

@headwinds
Created November 28, 2021 15:47
Show Gist options
  • Save headwinds/f20c5a4dd9492e54b75397458d41fa9b to your computer and use it in GitHub Desktop.
Save headwinds/f20c5a4dd9492e54b75397458d41fa9b to your computer and use it in GitHub Desktop.
Java: load json with Gson
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();
}
}
}
@headwinds
Copy link
Author

I would give credit to this article because I used most of that example only changed 1 line to use InputStreamReader instead of Files

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment