3

I would like to parse a local JSON file and marshal it into models using RestTemplate, but can't tell if this is possible.

I'm trying to pre-populate a database on an Android app that is using RestTemplate for syncing with the server. Rather than parsing the local JSON on my own, I thought, why not use RestTemplate? It's made exactly for parsing JSON into models.

But...I can't tell from the docs if there is any way to do this. There is the MappingJacksonHttpMessageConverter class which appears to convert the server's http response into a model...but is there any way to hack that to work with a local file? I tried, but kept getting deeper and deeper down the rabbit hole with no luck.

Nick Daugherty
  • 2,763
  • 4
  • 20
  • 17

2 Answers2

3

Figured this out. Instead of using RestTemplate, you can just use Jackson directly. There is no reason RestTemplate needs to be involved in this. It's 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);
}
Nick Daugherty
  • 2,763
  • 4
  • 20
  • 17
1

Yes, I think it is possible(with MappingJacksonHttpMessageConverter).

MappingJacksonHttpMessageConverter has method read() which takes two parameters: Class and HttpInputMessage

MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter();
YourClazz obj = (YourClazz) converter.read(YourClazz.class, new MyHttpInputMessage(myJsonString));

With this method you can read single object from single json message, but YourClazz can be some collection.

Next, You have to create you own HttpInputMessage implementation, in this example it expected json as string but You probably can pass stream to your json file.

public class MyHttpInputMessage implements HttpInputMessage {

    private String jsonString;

    public MyHttpInputMessage(String jsonString) {
        this.jsonString = jsonString;
    }

    public HttpHeaders getHeaders() {
        // no headers needed
        return null;
    }

    public InputStream getBody() throws IOException {
        InputStream is = new ByteArrayInputStream(
                jsonString.getBytes("UTF-8"));
        return is;
    }

}

PS. You can publish your app with database

Community
  • 1
  • 1
Leszek
  • 6,568
  • 3
  • 42
  • 53
  • Thanks for the good answer. I tried this method but kept getting an exception 'Can not deserialize instance of...'. I found a better solution which I'll share. – Nick Daugherty Jul 31 '12 at 22:50