001/*
002 * Copyright 2012-2018 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 *      http://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 */
016
017package org.springframework.boot.json;
018
019import java.util.List;
020import java.util.Map;
021
022import com.fasterxml.jackson.core.type.TypeReference;
023import com.fasterxml.jackson.databind.ObjectMapper;
024
025/**
026 * Thin wrapper to adapt Jackson 2 {@link ObjectMapper} to {@link JsonParser}.
027 *
028 * @author Dave Syer
029 * @see JsonParserFactory
030 */
031public class JacksonJsonParser extends AbstractJsonParser {
032
033        private static final TypeReference<?> MAP_TYPE = new MapTypeReference();
034
035        private static final TypeReference<?> LIST_TYPE = new ListTypeReference();
036
037        private ObjectMapper objectMapper; // Late binding
038
039        /**
040         * Creates an instance with the specified {@link ObjectMapper}.
041         * @param objectMapper the object mapper to use
042         */
043        public JacksonJsonParser(ObjectMapper objectMapper) {
044                this.objectMapper = objectMapper;
045        }
046
047        /**
048         * Creates an instance with a default {@link ObjectMapper} that is created lazily.
049         */
050        public JacksonJsonParser() {
051        }
052
053        @Override
054        public Map<String, Object> parseMap(String json) {
055                return tryParse(() -> getObjectMapper().readValue(json, MAP_TYPE),
056                                Exception.class);
057        }
058
059        @Override
060        public List<Object> parseList(String json) {
061                return tryParse(() -> getObjectMapper().readValue(json, LIST_TYPE),
062                                Exception.class);
063        }
064
065        private ObjectMapper getObjectMapper() {
066                if (this.objectMapper == null) {
067                        this.objectMapper = new ObjectMapper();
068                }
069                return this.objectMapper;
070        }
071
072        private static class MapTypeReference extends TypeReference<Map<String, Object>> {
073
074        }
075
076        private static class ListTypeReference extends TypeReference<List<Object>> {
077
078        }
079
080}