View Javadoc

1   /*
2    * $Id: JsonNodeExpressionEvaluator.java 20383 2010-11-29 19:44:13Z dfeist $
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  
11  package org.mule.module.json;
12  
13  import org.mule.routing.AbstractSplitter;
14  
15  import java.util.ArrayList;
16  import java.util.Iterator;
17  import java.util.List;
18  
19  import org.codehaus.jackson.JsonNode;
20  import org.codehaus.jackson.node.ArrayNode;
21  import org.codehaus.jackson.node.ValueNode;
22  
23  /**
24   * An JSON expression evaluator that returns {@link JsonNode}'s instead of strings.
25   * Arrays are still returned as a {@link List} rather than as an {@link ArrayNode} to
26   * enable splitting using the {@link AbstractSplitter}
27   * 
28   * @see org.mule.module.json.JsonData
29   * @see JsonExpressionEvaluator
30   */
31  public class JsonNodeExpressionEvaluator extends JsonExpressionEvaluator
32  {
33  
34      protected Object extractResultFromNode(JsonNode result)
35      {
36          if (result instanceof ValueNode)
37          {
38              return result.getValueAsText();
39          }
40          if (result instanceof ArrayNode)
41          {
42              List parts = new ArrayList<String>();
43              for (Iterator<JsonNode> i = ((JsonNode) result).getElements(); i.hasNext();)
44              {
45                  JsonNode arrayNode = i.next();
46                  parts.add(extractResultFromNode(arrayNode));
47              }
48              return parts;
49          }
50          else
51          {
52              return result;
53          }
54      }
55  
56      public String getName()
57      {
58          return "json-node";
59      }
60  }