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.google.gson.Gson;
023import com.google.gson.GsonBuilder;
024import com.google.gson.reflect.TypeToken;
025
026/**
027 * Thin wrapper to adapt {@link Gson} to a {@link JsonParser}.
028 *
029 * @author Dave Syer
030 * @author Jean de Klerk
031 * @since 1.2.0
032 * @see JsonParserFactory
033 */
034public class GsonJsonParser extends AbstractJsonParser {
035
036        private static final TypeToken<?> MAP_TYPE = new MapTypeToken();
037
038        private static final TypeToken<?> LIST_TYPE = new ListTypeToken();
039
040        private Gson gson = new GsonBuilder().create();
041
042        @Override
043        public Map<String, Object> parseMap(String json) {
044                return parseMap(json,
045                                (trimmed) -> this.gson.fromJson(trimmed, MAP_TYPE.getType()));
046        }
047
048        @Override
049        public List<Object> parseList(String json) {
050                return parseList(json,
051                                (trimmed) -> this.gson.fromJson(trimmed, LIST_TYPE.getType()));
052        }
053
054        private static final class MapTypeToken extends TypeToken<Map<String, Object>> {
055
056        }
057
058        private static final class ListTypeToken extends TypeToken<List<Object>> {
059
060        }
061
062}