Loading an object using Gson

Forgive me if this is trivial or impossible, but I have a moment on Monday morning.

I would like to create a method that implements some methods from the Gson library to load some parameters of Objects. Basically, I have a bunch of different settings objects, but I don’t want to get used to overriding the loading method for each class so that I want to have something like:

 public class ConfigLoader { public static void main(final String[] args) { final ConfigurationSettings loadedConfigSettigs = load("testSettings.json", ConfigurationSettings.class); final AlternativeConfigurationSettings alternativeConfigSettigs = load("testSettings2.json", AlternativeConfigurationSettings .class); } public T load(final InputStream inputStream, final Class<T> clazz) { try { if (inputStream != null) { final Gson gson = new Gson(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); return gson.fromJson(reader, clazz); } } catch (final Exception e) { } return null; } } 

where I can pass in the InputStream and the class of the object I want to return. Is there an easy way to do this (I don’t want to create a method for every class that I want to load, and also don’t want to create a specific loader for each class)?

+6
source share
1 answer

The following code works (requires Java 1.5 or higher):

 import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import com.google.gson.Gson; public class ConfigLoader { public static void main(final String[] args) { final ConfigurationSettings loadedConfigSettigs = load(new FileInputStream(new File("testSettings.json")), ConfigurationSettings.class); final AlternativeConfigurationSettings alternativeConfigSettigs = load(new FileInputStream(new File("testSettings2.json")), AlternativeConfigurationSettings.class); } public static <T> T load(final InputStream inputStream, final Class<T> clazz) { try { if (inputStream != null) { final Gson gson = new Gson(); final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); return gson.fromJson(reader, clazz); } } catch (final Exception e) { } return null; } } 
+10
source

Source: https://habr.com/ru/post/909994/


All Articles