View Javadoc

1   package org.springframework.batch.item.file.mapping;
2   
3   import java.util.Map;
4   
5   import org.codehaus.jackson.JsonParser;
6   import org.codehaus.jackson.map.MappingJsonFactory;
7   import org.springframework.batch.item.file.LineMapper;
8   
9   /**
10   * Interpret a line as a Json object and parse it up to a Map. The line should be a standard Json object, starting with
11   * "{" and ending with "}" and composed of <code>name:value</code> pairs separated by commas. Whitespace is ignored,
12   * e.g.
13   * 
14   * <pre>
15   * { "foo" : "bar", "value" : 123 }
16   * </pre>
17   * 
18   * The values can also be Json objects (which are converted to maps):
19   * 
20   * <pre>
21   * { "foo": "bar", "map": { "one": 1, "two": 2}}
22   * </pre>
23   * 
24   * @author Dave Syer
25   * 
26   */
27  public class JsonLineMapper implements LineMapper<Map<String, Object>> {
28  
29  	private MappingJsonFactory factory = new MappingJsonFactory();
30  
31  	/**
32  	 * Interpret the line as a Json object and create a Map from it.
33  	 * 
34  	 * @see LineMapper#mapLine(String, int)
35  	 */
36      @Override
37  	public Map<String, Object> mapLine(String line, int lineNumber) throws Exception {
38  		Map<String, Object> result;
39  		JsonParser parser = factory.createJsonParser(line);
40  		@SuppressWarnings("unchecked")
41  		Map<String, Object> token = parser.readValueAs(Map.class);
42  		result = token;
43  		return result;
44  	}
45  
46  }