JtecX JtecX - 3 months ago 15
Android Question

Point to Json File you created in Android Studio

Practing my JSON to JAVA Object skills, running into an issue, trying to point to the json file i created in android studio, instead of writing out my json data in full. here is my code. Thank you

Trying to turn this:

System.out.println(
gson.fromJson("{\"draw_date\":\"2016-10-07T00:00:00.000\",\"mega_ball\":\"14\",\"multiplier\":\"02\",\"winning_numbers\":\"24 37 42 50 65\"}", MegaPOJO.class));


Into This:

System.out.println(gson.fromJson(jsonFile, MegaPOJO.class));

Answer

If you want to do this, place the json file in the raw resources folder.

I created a ResourceManager class to get the content.

public class ResourceManager {

    private final Context context;
    private final Resources resources;
    private static ResourceManager resourceManager;

    private ResourceManager(Context context) {
        this.context = context;
        this.resources = context.getResources();
    }

    public static ResourceManager getResourceManager(Context context) {
        if (resourceManager == null) {
            resourceManager = new ResourceManager(context);
        }

        return resourceManager;
    }

    public String getJSONFromRawResources(String jsonFilename) {
        int resourceID = resources.getIdentifier(jsonFilename, "raw", context.getPackageName());

        InputStream inputStream = resources.openRawResource(resourceID);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder jsonStringStringBuilder = new StringBuilder();

            String line;
            while ((line = reader.readLine()) != null) {
                jsonStringStringBuilder.append(line);
            }

            return jsonStringStringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

You can access this class by:

ResourceManager resourceManager = ResourceManager.getResourceManager(this);
String jsonResult = resourceManager.getJSONFromRawResources("jsonfile");

And then you can use:

 System.out.println(gson.fromJson(jsonResult, MegaPOJO.class));