View Javadoc

1   /*
2    * $Id:  $
3    * -------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  package org.mule.module.json.transformers;
11  
12  
13  import org.mule.api.annotations.ContainsTransformerMethods;
14  import org.mule.api.annotations.Transformer;
15  import org.mule.tck.testmodels.fruit.Apple;
16  
17  import java.io.IOException;
18  import java.io.InputStream;
19  import java.io.StringWriter;
20  
21  import javax.annotation.PostConstruct;
22  
23  import org.codehaus.jackson.map.ObjectMapper;
24  
25  @ContainsTransformerMethods
26  public class JsonCustomTransformerWithMixins
27  {
28      private ObjectMapper mapper;
29  
30      @PostConstruct
31      public void init()
32      {
33          mapper = new ObjectMapper();
34          mapper.getSerializationConfig().addMixInAnnotations(Apple.class, AppleMixin.class);
35          mapper.getDeserializationConfig().addMixInAnnotations(Apple.class, AppleMixin.class);
36      }
37  
38      @Transformer(sourceTypes = {InputStream.class, byte[].class})
39      public Apple toApple(String in) throws IOException
40      {
41          return mapper.readValue(in, Apple.class);
42      }
43  
44      @Transformer
45      public String fromApple(Apple apple) throws IOException
46      {
47          StringWriter w = new StringWriter();
48          mapper.writeValue(w, apple);
49          return w.toString();
50  
51      }
52  
53  }