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