001/*
002 * Copyright 2009-2014 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.springframework.batch.item.file.mapping;
017
018import java.util.Map;
019
020import com.fasterxml.jackson.core.JsonParser;
021import com.fasterxml.jackson.databind.MappingJsonFactory;
022
023import org.springframework.batch.item.file.LineMapper;
024
025/**
026 * Interpret a line as a JSON object and parse it up to a Map. The line should be a standard JSON object, starting with
027 * "{" and ending with "}" and composed of <code>name:value</code> pairs separated by commas. Whitespace is ignored,
028 * e.g.
029 * 
030 * <pre>
031 * { "foo" : "bar", "value" : 123 }
032 * </pre>
033 * 
034 * The values can also be JSON objects (which are converted to maps):
035 * 
036 * <pre>
037 * { "foo": "bar", "map": { "one": 1, "two": 2}}
038 * </pre>
039 * 
040 * @author Dave Syer
041 * 
042 */
043public class JsonLineMapper implements LineMapper<Map<String, Object>> {
044
045        private MappingJsonFactory factory = new MappingJsonFactory();
046
047        /**
048         * Interpret the line as a Json object and create a Map from it.
049         * 
050         * @see LineMapper#mapLine(String, int)
051         */
052    @Override
053        public Map<String, Object> mapLine(String line, int lineNumber) throws Exception {
054                Map<String, Object> result;
055                JsonParser parser = factory.createParser(line);
056                @SuppressWarnings("unchecked")
057                Map<String, Object> token = parser.readValueAs(Map.class);
058                result = token;
059                return result;
060        }
061
062}