pI.generator.JsonJavaMapper.java Source code

Java tutorial

Introduction

Here is the source code for pI.generator.JsonJavaMapper.java

Source

/* JsonJavaMapper.java
 *
 * Copyright 2010-2011 Johannes Kepler Universitt Linz,
 * Institut fr Wissensbasierte Mathematische Systeme.
 *
 * This file is part of pureImage.
 *
 * pureImage is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * pureImage is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with pureImage. If not, see <http://www.gnu.org/licenses/>.
 */

package pI.generator;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

public class JsonJavaMapper {

    public JsonJavaMapper() {
    }

    public Object convert(JsonElement root) {
        return json2Java(root);
    }

    public Object json2Java(JsonElement elem) {
        if (elem.isJsonArray()) {
            return jsonArrayAsList(elem.getAsJsonArray());
        } else if (elem.isJsonPrimitive()) {
            return json2JavaPrimitive(elem.getAsJsonPrimitive());
        } else {
            return jsonObject2Map(elem.getAsJsonObject());
        }
    }

    @SuppressWarnings({ "unchecked" })
    public List jsonArrayAsList(JsonArray arr) {
        ArrayList list = new ArrayList(arr.size());
        for (int j = 0; j < arr.size(); j++) {
            list.add(json2Java(arr.get(j)));
        }
        return list;
    }

    @SuppressWarnings({ "unchecked" })
    public Map jsonObject2Map(JsonObject obj) {
        LinkedHashMap map = new LinkedHashMap();
        for (Entry<String, JsonElement> entry : obj.entrySet()) {
            map.put(entry.getKey(), json2Java(entry.getValue()));
        }
        return map;
    }

    public Object json2JavaPrimitive(JsonPrimitive prim) {
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            return prim.getAsNumber();
        } else {
            throw new IllegalStateException();
        }
    }

}