Sonoman
Sonoman

Reputation: 3429

Load an Object using Gson

Forgive me if this is trivial or not possible but I'm having a Monday morning moment here.

I'd like to create a method that implements some methods from the Gson library to loaded some settings Objects. Basically, I have a bunch of different settings objects but I don't want to habe to override the load method for each class to I'd like 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 a simple way to do this (I don't want to have to create a method for each Class I want to be able to load, nor do I want to have to create a specific loader for each class)?

Upvotes: 7

Views: 18777

Answers (1)

Guillaume Polet
Guillaume Polet

Reputation: 47607

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

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;
    }
}

Upvotes: 13

Related Questions