PageRenderTime 58ms CodeModel.GetById 45ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/sitebricks-client/src/main/java/com/google/sitebricks/client/transport/JacksonJsonTransport.java

http://github.com/dhanji/sitebricks
Java | 48 lines | 34 code | 11 blank | 3 comment | 0 complexity | 4a7f2d61a986000850671f745c8d78fd MD5 | raw file
 1package com.google.sitebricks.client.transport;
 2
 3import java.io.IOException;
 4import java.io.InputStream;
 5import java.io.OutputStream;
 6
 7import com.fasterxml.jackson.databind.ObjectMapper;
 8import com.fasterxml.jackson.databind.type.TypeFactory;
 9import com.google.inject.TypeLiteral;
10import com.google.inject.Inject;
11import com.google.inject.Singleton;
12
13/**
14 * @author Dhanji R. Prasanna (dhanji@gmail.com)
15 */
16@Singleton
17public class JacksonJsonTransport extends Json {
18
19  private final ObjectMapper objectMapper;
20
21  @Inject
22  public JacksonJsonTransport(ObjectMapper objectMapper) {
23    this.objectMapper = objectMapper;
24  }  
25  
26  public ObjectMapper getObjectMapper() {
27    return objectMapper;
28  }
29  
30  public <T> T in(InputStream in, Class<T> type) throws IOException {
31    return objectMapper.readValue(in, type);
32  }
33
34  @Override
35  public <T> T in(InputStream in, TypeLiteral<T> type) throws IOException {
36    return objectMapper.readValue(in, TypeFactory.defaultInstance().constructType(type.getType()));
37  }
38
39  public <T> void out(OutputStream out, Class<T> type, T data) {
40    try {
41      objectMapper.writeValue(out, data);
42    } catch (IOException e) {
43      throw new RuntimeException(e);
44    }
45  }
46
47
48}