Java – Use RestTemplate to parse local JSON files

Use RestTemplate to parse local JSON files… here is a solution to the problem.

Use RestTemplate to parse local JSON files

I want to parse the local JSON file and encode it into the model using RestTemplate, but don’t know if this works.

I’m trying to prepopulate a database on an Android app that uses RestTemplate to sync with the server. I thought, instead of parsing the local JSON yourself, why not use RestTemplate? It is designed for parsing JSON into models.

But… I have no way to tell from the documentation if there is any way to do this. There is a MappingJacksonHttpMessageConverter class that seems to convert the server’s http response into a model… But is there any way to hack it to use local files? I tried, but kept sinking deeper and deeper down the rabbit hole, but no luck.

Solution

Figured it out. You can use Jackson directly instead of using RestTemplate. There’s no reason why RestTemplate needs to be involved. Very simple.

try {
    ObjectMapper mapper = new ObjectMapper();

InputStream jsonFileStream = context.getAssets().open("categories.json");

Category[] categories = (Category[]) mapper.readValue(jsonFileStream, Category[].class);

Log.d(tag, "Found "  + String.valueOf(categories.length) + " categories!!");
} catch (Exception e){
    Log.e(tag, "Exception", e);
}

Related Problems and Solutions