Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

In this page you can find the example usage for org.json JSONObject get.

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:tectonicus.blockTypes.BlockRegistry.java

public void deserializeBlockstates() {
    List<BlockVariant> blockVariants = new ArrayList<>();

    Enumeration<? extends ZipEntry> entries = zips.getBaseEntries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        String entryName = entry.getName();
        if (entryName.contains("blockstates")) {
            ZipStackEntry zse = zips.getEntry(entryName);
            try {
                JSONObject obj = new JSONObject(FileUtils.loadJSON(zse.getInputStream()));
                JSONObject variants = obj.getJSONObject("variants");

                Iterator<?> keys = variants.keys();
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    Object variant = variants.get(key);

                    blockVariants.add(BlockVariant.deserializeVariant(key, variant));
                }//from  w ww.j a  v a2s .  c o m
            } catch (Exception e) {
                e.printStackTrace();
            }

            String name = "minecraft:"
                    + StringUtils.removeEnd(entryName.substring(entryName.lastIndexOf("/") + 1), ".json");
            blockStates.put(name, blockVariants);
        }
    }
}

From source file:tectonicus.blockTypes.BlockRegistry.java

public BlockModel loadModel(String modelPath, ZipStack zips, Map<String, String> textureMap) throws Exception {
    ZipStackEntry modelFile = zips.getEntry("assets/minecraft/models/" + modelPath + ".json");

    JSONObject obj = new JSONObject(FileUtils.loadJSON(modelFile.getInputStream()));
    String parent = "";
    if (obj.has("parent")) // Get texture information and then load parent file
    {//from  w  w  w .  ja  v a 2 s . c  o  m
        parent = obj.getString("parent");

        return loadModel(parent, zips, populateTextureMap(textureMap, obj.getJSONObject("textures")));
    } else //Load all elements
    {
        Map<String, String> combineMap = new HashMap<>(textureMap);
        if (obj.has("textures")) {
            combineMap.putAll(populateTextureMap(textureMap, obj.getJSONObject("textures")));
        }

        List<BlockElement> elementsList = new ArrayList<>();

        boolean ao = true;
        if (obj.has("ambientocclusion"))
            ao = false;

        JSONArray elements = obj.getJSONArray("elements");
        for (int i = 0; i < elements.length(); i++) {
            Map<String, ElementFace> elementFaces = new HashMap<>();

            JSONObject element = elements.getJSONObject(i);

            JSONArray from = element.getJSONArray("from");
            Vector3f fromVector = new Vector3f((float) from.getDouble(0), (float) from.getDouble(1),
                    (float) from.getDouble(2));
            JSONArray to = element.getJSONArray("to");
            Vector3f toVector = new Vector3f((float) to.getDouble(0), (float) to.getDouble(1),
                    (float) to.getDouble(2));

            Vector3f rotationOrigin = new Vector3f(8.0f, 8.0f, 8.0f);
            String rotationAxis = "y";
            float rotationAngle = 0;
            boolean rotationScale = false;

            if (element.has("rotation")) {
                JSONObject rot = element.getJSONObject("rotation");
                JSONArray rotOrigin = rot.getJSONArray("origin");
                rotationOrigin = new Vector3f((float) rotOrigin.getDouble(0), (float) rotOrigin.getDouble(1),
                        (float) rotOrigin.getDouble(2));

                rotationAxis = rot.getString("axis");

                rotationAngle = (float) rot.getDouble("angle");

                if (element.has("rescale"))
                    rotationScale = true;
            }

            boolean shaded = true;
            if (element.has("shade"))
                shaded = false;

            JSONObject faces = element.getJSONObject("faces");

            Iterator<?> keys = faces.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONObject face = (JSONObject) faces.get(key);

                float u0 = fromVector.x();
                float v0 = fromVector.y();
                float u1 = toVector.x();
                float v1 = toVector.y();

                int rotation = 0;
                if (face.has("rotation"))
                    rotation = face.getInt("rotation");

                //System.out.println("u0="+u0+" v0="+v0+" u1="+u1+" v1="+v1);
                // TODO: Need to test more texture packs
                SubTexture subTexture = new SubTexture(null, u0 * (1.0f / 16.0f), v0 * (1.0f / 16.0f),
                        u1 * (1.0f / 16.0f), v1 * (1.0f / 16.0f));

                StringBuilder tex = new StringBuilder(face.getString("texture"));
                if (tex.charAt(0) == '#') {
                    String texture = tex.deleteCharAt(0).toString();

                    SubTexture te = texturePack
                            .findTexture(StringUtils.removeStart(combineMap.get(texture), "blocks/") + ".png");

                    final float texHeight = te.texture.getHeight();
                    final float texWidth = te.texture.getWidth();
                    final int numTiles = te.texture.getHeight() / te.texture.getWidth();

                    u0 = fromVector.x() / texWidth;
                    v0 = fromVector.y() / texWidth;
                    u1 = toVector.x() / texWidth;
                    v1 = toVector.y() / texWidth;

                    if (face.has("uv")) {
                        //System.out.println("Before: u0="+u0+" v0="+v0+" u1="+u1+" v1="+v1);
                        JSONArray uv = face.getJSONArray("uv");
                        u0 = (float) (uv.getDouble(0) / 16.0f);
                        v0 = (float) (uv.getDouble(1) / 16.0f) / numTiles;
                        u1 = (float) (uv.getDouble(2) / 16.0f);
                        v1 = (float) (uv.getDouble(3) / 16.0f) / numTiles;
                    }

                    System.out.println(texWidth + " x " + texHeight);
                    int frame = 1;
                    if (numTiles > 1) {
                        Random rand = new Random();
                        frame = rand.nextInt(numTiles) + 1;
                    }

                    subTexture = new SubTexture(te.texture, u0,
                            v0 + (float) (frame - 1) * (texWidth / texHeight), u1,
                            v1 + (float) (frame - 1) * (texWidth / texHeight));
                    //subTexture = new SubTexture(test, u0, v0, u1, v1);
                    //System.out.println("u0="+subTexture.u0+" v0="+subTexture.v0+" u1="+subTexture.u1+" v1="+subTexture.v1);
                }

                boolean cullFace = false;
                if (face.has("cullface"))
                    cullFace = true;

                boolean tintIndex = false;
                if (face.has("tintindex"))
                    tintIndex = true;

                ElementFace ef = new ElementFace(subTexture, cullFace, rotation, tintIndex);
                elementFaces.put(key, ef);
            }

            BlockElement be = new BlockElement(fromVector, toVector, rotationOrigin, rotationAxis,
                    rotationAngle, rotationScale, shaded, elementFaces);
            elementsList.add(be);
        }

        return new BlockModel(modelPath, ao, elementsList);
    }
}

From source file:tectonicus.blockTypes.BlockRegistry.java

private Map<String, String> populateTextureMap(Map<String, String> textureMap, JSONObject textures)
        throws JSONException {
    Map<String, String> newTexMap = new HashMap<>();

    Iterator<?> keys = textures.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        StringBuilder tex = new StringBuilder((String) textures.get(key));
        if (tex.charAt(0) == '#') {
            newTexMap.put(key, textureMap.get(tex.deleteCharAt(0).toString()));
        } else {//from  w w w . jav  a2s.  c  om
            newTexMap.put(key, tex.toString());
        }
    }
    return newTexMap;
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.AppReferenceObj.java

@Override
public void activate(Context context, SignedObj obj) {
    JSONObject content = obj.getJson();
    if (DBG)/*from w w w.ja  va  2 s  . c o m*/
        Log.d(TAG, "activating from appReferenceObj: " + content);

    if (!content.has(DbObject.CHILD_FEED_NAME)) {
        Log.wtf(TAG, "Bad app reference found.");
        Toast.makeText(context, "Could not launch application.", Toast.LENGTH_SHORT).show();
        return;
    }

    Log.w(TAG, "Using old-school app launch");
    SignedObj appContent = getAppStateForChildFeed(context, obj);
    if (appContent == null) {
        Intent launch = AppStateObj.getLaunchIntent(context, obj);
        if (!(context instanceof Activity)) {
            launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }

        context.startActivity(launch);
    } else {
        if (DBG)
            Log.d(TAG, "pulled app state " + appContent);
        try {
            appContent.getJson().put(PACKAGE_NAME, content.get(PACKAGE_NAME));
            appContent.getJson().put(OBJ_INTENT_ACTION, content.get(OBJ_INTENT_ACTION));
            appContent.getJson().put(DbObject.CHILD_FEED_NAME, content.get(DbObject.CHILD_FEED_NAME));
        } catch (JSONException e) {
        }
        //mAppStateObj.activate(context, appContent);
        Log.wtf(TAG, "dead code exception");
    }
}

From source file:com.yoloci.fileupload.BundleJSONConverter.java

public static Bundle convertToBundle(JSONObject jsonObject) throws JSONException {
    Bundle bundle = new Bundle();
    @SuppressWarnings("unchecked")
    Iterator<String> jsonIterator = jsonObject.keys();
    while (jsonIterator.hasNext()) {
        String key = jsonIterator.next();
        Object value = jsonObject.get(key);
        if (value == null || value == JSONObject.NULL) {
            // Null is not supported.
            continue;
        }//  ww  w.  j  a va  2s . c o  m

        // Special case JSONObject as it's one way, on the return it would be Bundle.
        if (value instanceof JSONObject) {
            bundle.putBundle(key, convertToBundle((JSONObject) value));
            continue;
        }

        Setter setter = SETTERS.get(value.getClass());
        if (setter == null) {
            throw new IllegalArgumentException("Unsupported type: " + value.getClass());
        }
        setter.setOnBundle(bundle, key, value);
    }

    return bundle;
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private Bundle authFailedNotification(JSONObject result, String username) {
    Bundle user_notification_bundle = new Bundle();
    try {/*from  w  w  w.j  a  va 2s . c  o m*/
        JSONObject error_message = result.getJSONObject(ERRORS);
        String error_type = error_message.keys().next().toString();
        String message = error_message.get(error_type).toString();
        user_notification_bundle.putString(getResources().getString(R.string.user_message), message);
    } catch (JSONException e) {
    }

    if (!username.isEmpty())
        user_notification_bundle.putString(SessionDialog.USERNAME, username);
    user_notification_bundle.putBoolean(RESULT_KEY, false);

    return user_notification_bundle;
}

From source file:com.air.RecipeFinder.java

public static JSONArray trigger(JSONObject object)
        throws UnirestException, IOException, JSONException, ParseException {

    //JSONObject object = getJsonObject();

    System.out.println("recieved object : " + object.toString());
    Calendar calendar = Calendar.getInstance();
    String timestamp = calendar.getTime().toString().replaceAll("\\s+:", "").replaceAll(":", "");
    String cuisine = object.getJSONObject("query").getString("cuisine").replaceAll(" ", "+").replaceAll(",",
            "%2C");
    String excludeIngredients = object.getJSONObject("query").getString("excludeIngredients")
            .replaceAll(" ", "+").replaceAll(",", "%2C");
    String includeIngredients = object.getJSONObject("query").getString("includeIngredients")
            .replaceAll(" ", "+").replaceAll(",", "%2C");
    String intolerances = object.getJSONObject("query").getString("intolerances").replaceAll(" ", "+")
            .replaceAll(",", "%2C");
    String maxCalories = object.getJSONObject("query").getString("maxCalories");
    String maxCarbs = object.getJSONObject("query").getString("maxCarbs");
    String maxFat = object.getJSONObject("query").getString("maxFat");
    String maxProtein = object.getJSONObject("query").getString("maxProtein");
    String minCalories = object.getJSONObject("query").getString("minCalories");
    String minCarbs = object.getJSONObject("query").getString("minCarbs");
    String minFat = object.getJSONObject("query").getString("minFat");
    String minProtein = object.getJSONObject("query").getString("minProtein");
    String query = object.getJSONObject("query").getString("querywords").replaceAll(" ", "+").replaceAll(",",
            "%2C");
    String type = "".replaceAll(" ", "+");
    String disease = object.getString("disease");
    //System.out.println(disease);

    if (query.length() > 1) {
        query = query.substring(1);/* ww w. j a  v  a2s .  c  om*/
    }
    /*
    ZoneId zoneIdParis = ZoneId.of( "America/New_York" );
    LocalDateTime dateTime = LocalDateTime.now( zoneIdParis);
    String temp=dateTime.toString().split("T")[1];
    System.out.println(temp);
     */

    @SuppressWarnings("deprecation")
    int hours = new Date().getHours();
    System.out.println("hours:  " + hours);

    if (hours >= 5 && hours <= 10) {
        type = type + "breakfast";
    } else if (hours > 10 && hours <= 12) {
        type = type + "brunch";
    } else if (hours > 12 && hours <= 15 || hours > 18 && hours <= 23) {
        type = type + "main+course";
    } else if (hours > 23 || hours < 5 || hours > 15 && hours <= 18) {
        type = type + "snacks";
    }
    System.out.println();

    /*   double weight = Integer.parseInt(object.getString("weight"));
       String unit_weight=object.getString("weightIN");
       if(unit_weight.equals("pounds")){
          weight=weight/2.2;
       }
            
       double height = 0.0;
       String unit_height=object.getString("heightIN");
       if (unit_height.equals("ft"))
       {
          height=height/2.2;
       }*/

    /*
    double bmi = 0.0;
            
    bmi = ((weight * 703)/(height * height));
            
            
            
            
    System.out.println("BMI VALUES");
    System.out.println("Underweight: Under 18.5");
    System.out.println("Normal: 18.5-24.9 ");
    System.out.println("Overweight: 25-29.9");
    System.out.println("Obese: 30 or over");
     */
    //////////////////////////////////////////////
    double weight = Double.parseDouble(object.getString("weight"));
    String unit_weight = object.getString("weightIN");
    if (unit_weight.equals("pounds")) {
        weight = weight * 0.45;
    }
    System.out.println(weight);
    double height = Double.parseDouble(object.getString("height"));
    String unit_height = object.getString("heightIN");
    System.out.println(height);

    if (unit_height.equals("ft")) {
        height = height * 0.025;
    }

    System.out.println(height);

    double bmi = 0.0;

    bmi = ((weight) / (height * height));

    int age = Integer.parseInt(object.getString("age"));
    String Gender = object.getString("gender");
    double[] maleActivities = { 1, 1.11, 1.26, 1.48 };
    double[] femaleActivities = { 1, 1.12, 1.27, 1.45 };
    //String[] PhysicalActivity={"Sedentary (no exercise)","Low active (walks about 2 miles daily at 3-4 mph)","Active (walks about 7 miles daily at 3-4 mph)","Very active (walks about 17 miles daily at 3-4 mph)"};
    double calories = 0.0;
    double userMaxCal = Double.parseDouble(maxCalories);
    if (Gender.equals("male")) {
        calories = 662 - (6.91 * age)
                + (maleActivities[Integer.parseInt(object.getString("activityLevel"))] * 15.91 * weight)
                + (539.6 * height);
    } else {
        calories = 354 - (6.91 * age)
                + (femaleActivities[Integer.parseInt(object.getString("activityLevel"))] * 9.36 * weight)
                + (726 * height);
    }

    if (userMaxCal > calories) {
        //   maxCalories=String.valueOf(calories);
    }

    //List<String> words= new ArrayList<String>();

    //words= getSuggestions("Olrves", 2);
    //System.out.println(words.toString());
    ////////////////////////////////////////////////////////////////////      

    //original recipes
    //String url = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/searchComplex?cuisine="+cuisine+"&excludeIngredients="+excludeIngredients+"&includeIngredients="+includeIngredients+"&intolerances="+intolerances+"&limitLicense=false&maxCalories="+maxCalories+"+&maxCarbs="+maxCarbs+"&maxFat="+maxFat+"&maxProtein="+maxProtein+"&minCalories="+minCalories+"&minCarbs="+minCarbs+"&minFat="+minFat+"&minProtein="+minProtein+"&number=100&offset=0&query="+query+"&ranking=1&type="+type;
    String url = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/searchComplex?cuisine="
            + cuisine + "&fillIngredients=false";
    if (intolerances != "") {
        url += "&intolerances=" + intolerances;
    }
    if (includeIngredients != "") {
        url += "&includeIngredients=" + includeIngredients;
    } else {
        url += "&includeIngredients=salt";
    }
    url += "&limitLicense=false&maxCalories=" + maxCalories + "&maxCarbs=" + maxCarbs + "&maxFat=" + maxFat
            + "&maxProtein=" + maxProtein + "&minCalories=" + minCalories + "&minCarbs=" + minCarbs + "&minFat="
            + minFat + "&minProtein=" + minProtein + "&number=100&offset=0&query=" + query + "&ranking=1"
            + "&type=" + type;

    //System.out.println("url : " + url);

    HttpResponse<String> response = Unirest.get(url)
            //EzPVzV3OIImshUC16NzTUL4Q9zE5p1fS8uIjsnHrZlqZDU38BN

            .header("X-Mashape-Key", "q8OegLa2iqmshvbsYklWvajeDcqZp1e63fSjsnmhLIw9xoIlw1").asString();
    System.out.println(
            "**********************************Just before printing url********************************");
    System.out.println("url : " + url);
    System.out.println("response.getBody() : " + response.getBody());
    System.out.println(
            "**********************************Just after printing url********************************");

    //String filename="air_"+timestamp+".json";
    //FileWriter filewriter = new FileWriter(filename);

    //filewriter.write(response.getBody().toString());
    //filewriter.write(response.getBody().toString());
    //filewriter.close();
    //FileReader filereader = new FileReader(filename);
    //BufferedReader br = new BufferedReader(filereader);
    //System.out.println(br.readLine());
    //JSONObject a = new JSONObject(br.readLine());
    //System.out.println(a);
    //JSONArray getArray = a.getJSONArray("results");
    ArrayList<String> al = new ArrayList<>();
    JSONObject res = new JSONObject(response.getBody().toString());
    org.json.JSONArray recipes = res.getJSONArray("results");
    System.out.println(recipes.toString());
    for (int i = 0; i < recipes.length(); i++) {
        JSONObject ids = recipes.getJSONObject(i);
        //System.out.println(ids.get("id").toString());
        al.add(ids.get("id").toString());

    }
    ArrayList<HashMap<String, Float>> xmlresult = new ArrayList<HashMap<String, Float>>();
    System.out.println("*****************************before xmlParser****************************");
    XMLParser xmlParse = new XMLParser();
    xmlresult = xmlParse.xmlparser(disease);
    System.out.println("*****************************after xmlParser****************************");
    //System.out.println(xmlresult.get(0).toString());
    //System.out.println(xmlresult.get(1).toString());
    //System.out.println(response.getBody());
    System.out.println("al :" + al);
    System.out.println("xmlResult : " + xmlresult);
    return (JsonParser.jsonparser(al, xmlresult, recipes, disease));

}

From source file:com.soomla.store.domain.PurchasableVirtualItem.java

/**
 * see parent// w  ww. ja v  a  2s . c  o m
 */
@Override
public JSONObject toJSONObject() {
    JSONObject parentJsonObject = super.toJSONObject();
    JSONObject jsonObject = new JSONObject();
    try {
        Iterator<?> keys = parentJsonObject.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            jsonObject.put(key, parentJsonObject.get(key));
        }

        JSONObject purchasableObj = new JSONObject();

        if (mPurchaseType instanceof PurchaseWithMarket) {
            purchasableObj.put(JSONConsts.PURCHASE_TYPE, JSONConsts.PURCHASE_TYPE_MARKET);

            GoogleMarketItem mi = ((PurchaseWithMarket) mPurchaseType).getGoogleMarketItem();
            purchasableObj.put(JSONConsts.PURCHASE_MARKET_ITEM, mi.toJSONObject());
        } else if (mPurchaseType instanceof PurchaseWithVirtualItem) {
            purchasableObj.put(JSONConsts.PURCHASE_TYPE, JSONConsts.PURCHASE_TYPE_VI);

            purchasableObj.put(JSONConsts.PURCHASE_VI_ITEMID,
                    ((PurchaseWithVirtualItem) mPurchaseType).getTargetItemId());
            purchasableObj.put(JSONConsts.PURCHASE_VI_AMOUNT,
                    ((PurchaseWithVirtualItem) mPurchaseType).getAmount());
        }

        jsonObject.put(JSONConsts.PURCHASABLE_ITEM, purchasableObj);
    } catch (JSONException e) {
        StoreUtils.LogError(TAG, "An error occurred while generating JSON object.");
    }

    return jsonObject;
}

From source file:com.vk.sdk.util.VKJsonHelper.java

/**
 * Converts selected json-object to map//w  w  w. ja v  a  2  s . co  m
 *
 * @param object object to convert
 * @return Filled map
 * @throws JSONException
 */
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap<String, Object>();
    Iterator keys = object.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        map.put(key, fromJson(object.get(key)));
    }
    return map;
}

From source file:com.whizzosoftware.hobson.mqtt.MQTTMessageHandler.java

protected Collection<VariableUpdate> createVariableUpdates(String deviceId, JSONObject json) {
    List<VariableUpdate> updates = new ArrayList<>();
    for (Object o : json.keySet()) {
        String key = o.toString();
        updates.add(new VariableUpdate(VariableContext.create(DeviceContext.create(ctx, deviceId), key),
                json.get(key)));
    }/*w  ww. jav a  2  s . c o m*/
    return updates;
}