Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Main {

    @SuppressWarnings("unchecked")
    public static <T> T getJsonObjectValue(String json, String key, Class<T> clazz) {
        try {
            return getJsonObjectValue(new JSONObject(json), key, clazz);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getJsonObjectValue(JSONObject jsonObject, String key, Class<T> clazz) {
        T t = null;
        try {
            if (clazz == Integer.class) {
                t = (T) Integer.valueOf(jsonObject.getInt(key));
            } else if (clazz == Boolean.class) {
                t = (T) Boolean.valueOf(jsonObject.getBoolean(key));
            } else if (clazz == String.class) {
                t = (T) String.valueOf(jsonObject.getString(key));
            } else if (clazz == Double.class) {
                t = (T) Double.valueOf(jsonObject.getDouble(key));
            } else if (clazz == JSONObject.class) {
                t = (T) jsonObject.getJSONObject(key);
            } else if (clazz == JSONArray.class) {
                t = (T) jsonObject.getJSONArray(key);
            } else if (clazz == Long.class) {
                t = (T) Long.valueOf(jsonObject.getLong(key));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return t;
    }
}