Example usage for org.json JSONObject NULL

List of usage examples for org.json JSONObject NULL

Introduction

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

Prototype

Object NULL

To view the source code for org.json JSONObject NULL.

Click Source Link

Document

It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value.

Usage

From source file:eu.sathra.io.IO.java

private Object[] parseParams(Class<?> paramTypes[], String params[], String[] defaults, JSONObject jObj)
        throws ArrayIndexOutOfBoundsException, IllegalArgumentException, Exception {

    Object[] parsed = new Object[paramTypes.length];

    for (int c = 0; c < params.length; ++c) {
        String param = params[c];
        String defaultValue = defaults == null ? null : defaults[c];
        Class<?> myType = paramTypes[c];

        if (!jObj.has(param)) {
            /*// w ww  .j  a  v a  2 s. c  o  m
             * JSON element not found, that means we have to use default
             * value
             */
            jObj.put(param, defaultValue == null ? JSONObject.NULL : defaultValue);
        }

        //Log.debug("Deserializing: " + myType + " " + jObj.get(param));

        parsed[c] = getValue(jObj, param, myType);
    }

    return parsed;
}

From source file:com.jsonstore.jackson.JsonOrgJSONArrayDeserializer.java

@Override
public JSONArray deserialize(JsonParser parser, DeserializationContext context)
        throws IOException, JsonProcessingException {
    JSONArray result = new JacksonSerializedJSONArray();
    JsonToken token = parser.nextToken();

    while (token != JsonToken.END_ARRAY) {
        switch (token) {
        case START_ARRAY: {
            result.put(deserialize(parser, context));

            break;
        }// w  w  w  .  j av a 2  s.c  o m

        case START_OBJECT: {
            result.put(JsonOrgJSONObjectDeserializer.instance.deserialize(parser, context));

            break;
        }

        case VALUE_EMBEDDED_OBJECT: {
            result.put(parser.getEmbeddedObject());

            break;
        }

        case VALUE_FALSE: {
            result.put(Boolean.FALSE);

            break;
        }

        case VALUE_NULL: {
            result.put(JSONObject.NULL);

            break;
        }

        case VALUE_NUMBER_FLOAT: {
            result.put(parser.getNumberValue());

            break;
        }

        case VALUE_NUMBER_INT: {
            result.put(parser.getNumberValue());

            break;
        }

        case VALUE_STRING: {
            result.put(parser.getText());

            break;
        }

        case VALUE_TRUE: {
            result.put(Boolean.TRUE);

            break;
        }

        case END_ARRAY:
        case END_OBJECT:
        case FIELD_NAME:
        case NOT_AVAILABLE: {
            break;
        }
        }

        token = parser.nextToken();
    }

    return result;
}

From source file:org.uiautomation.ios.IOSCapabilities.java

public Object getCapability(String key) {
    Object o = getRawCapabilities().get(key);
    if (o != null && o.equals(JSONObject.NULL)) {
        return null;
    } else {/*from  www. ja  v a  2 s  .co m*/
        return o;
    }

}

From source file:de.fahrgemeinschaft.FahrgemeinschaftConnector.java

@Override
public long search(Ride query) throws Exception {
    HttpURLConnection get;//  ww  w.j  a  v  a  2  s . co  m
    StringBuffer url = new StringBuffer().append(endpoint).append(TRIP);
    if (query == null) { // myrides
        get = (HttpURLConnection) new URL(endpoint + TRIP).openConnection();
    } else {
        startDate = df.format(query.getDep());
        try {
            if (query.getFrom() != null) {
                JSONObject from_json = new JSONObject();
                from_json.put(LONGITUDE, query.getFrom().getLng());
                from_json.put(LATITUDE, query.getFrom().getLat());
                from_json.put(TOLERANCE_RADIUS, get(RADIUS_FROM));
                from_json.put(STARTDATE, df.format(query.getDep()));
                from_json.put(REOCCUR, JSONObject.NULL);
                url.append(SEARCH_ORIGIN).append(from_json);
            }
            if (query.getTo() != null) {
                JSONObject to_json = new JSONObject();
                to_json.put(LONGITUDE, query.getTo().getLng());
                to_json.put(LATITUDE, query.getTo().getLat());
                to_json.put(TOLERANCE_RADIUS, get(RADIUS_TO));
                if (query.getFrom() == null) {
                    to_json.put(STARTDATE, df.format(query.getDep()));
                    url.append(ONLY_DESTINATION).append(to_json);
                } else {
                    url.append(SEARCH_DESTINATION).append(to_json);
                }
            }
            // place.put("Starttime", JSONObject.NULL);
            // place.put("ToleranceDays", "3");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        get = (HttpURLConnection) new URL(url.toString()).openConnection();
    }
    get.setRequestProperty("User-Agent", USER_AGENT);
    get.setRequestProperty(APIKEY, Secret.APIKEY);
    if (getAuth() != null)
        get.setRequestProperty(AUTHKEY, getAuth());
    JSONObject json = loadJson(get);
    if (get.getResponseCode() == 403)
        throw new AuthException();
    if (json != null) {
        JSONArray results = json.getJSONArray(RESULTS);
        System.out.println("FOUND " + results.length() + " rides");

        for (int i = 0; i < results.length(); i++) {
            store(parseRide(results.getJSONObject(i)));
        }
    }
    startDate = null;
    if (query != null)
        return getNextDayMorning(query.getDep());
    else
        return 0;
}

From source file:org.jabsorb.ng.serializer.impl.ArraySerializer.java

@Override
public Object marshall(final SerializerState state, final Object p, final Object o) throws MarshallException {

    try {/*w w w . ja v  a  2  s  .c o  m*/
        final JSONArray arr = new JSONArray();
        if (o instanceof int[]) {
            final int a[] = (int[]) o;
            for (int i = 0; i < a.length; i++) {
                arr.put(a[i]);
            }
        } else if (o instanceof long[]) {
            final long a[] = (long[]) o;
            for (int i = 0; i < a.length; i++) {
                arr.put(a[i]);
            }
        } else if (o instanceof short[]) {
            final short a[] = (short[]) o;
            for (int i = 0; i < a.length; i++) {
                arr.put(a[i]);
            }
        } else if (o instanceof byte[]) {
            final byte a[] = (byte[]) o;
            for (int i = 0; i < a.length; i++) {
                arr.put(a[i]);
            }
        } else if (o instanceof float[]) {
            final float a[] = (float[]) o;
            for (int i = 0; i < a.length; i++) {
                arr.put(a[i]);
            }
        } else if (o instanceof double[]) {
            final double a[] = (double[]) o;
            for (int i = 0; i < a.length; i++) {
                arr.put(a[i]);
            }
        } else if (o instanceof char[]) {
            final char a[] = (char[]) o;
            for (int i = 0; i < a.length; i++) {
                arr.put(a[i]);
            }
        } else if (o instanceof boolean[]) {
            final boolean a[] = (boolean[]) o;
            for (int i = 0; i < a.length; i++) {
                arr.put(a[i]);
            }
        } else if (o instanceof Object[]) {
            final Object a[] = (Object[]) o;
            for (int i = 0; i < a.length; i++) {
                final Object json = ser.marshall(state, o, a[i], new Integer(i));
                if (JSONSerializer.CIRC_REF_OR_DUPLICATE == json) {
                    // if dup or circ ref found, put a null slot in
                    // the array to maintain the array numbering for the
                    // fixups
                    arr.put(JSONObject.NULL);
                } else {
                    arr.put(json);
                }
            }
        }
        return arr;

    } catch (final JSONException e) {
        throw new MarshallException(e.getMessage() + " threw json exception", e);
    }

}

From source file:io.teak.sdk.Helpers.java

static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
    Map<String, Object> retMap = new HashMap<>();

    if (json != JSONObject.NULL) {
        retMap = toMap(json);/*  w ww. j a v a 2  s  . c o m*/
    }
    return retMap;
}

From source file:org.loklak.harvester.TwitterAPI.java

/**
 * enrich the user data with geocoding information
 * @param map the user json/* w w  w .  j ava2s . c  om*/
 */
public static void enrichLocation(JSONObject map) {

    // if a location is given, try to reverse geocode to get country name, country code and coordinates
    String location = map.has("location") ? (String) map.get("location") : null;

    // in case that no location is given, we try to hack that information out of the context
    if (location == null || location.length() == 0) {
        // sometimes the time zone contains city names! Try that
        String time_zone = map.has("time_zone") && map.get("time_zone") != JSONObject.NULL
                ? (String) map.get("time_zone")
                : null;
        if (time_zone != null && time_zone.length() > 0) {
            GeoMark loc = DAO.geoNames.analyse(time_zone, null, 5, "");
            // check if the time zone was actually a location name
            if (loc != null && loc.getNames().contains(time_zone)) {
                // success! It's just a guess, however...
                location = time_zone;
                map.put("location", location);
                //DAO.log("enrichLocation: TRANSLATED time_zone to location '" + location + "'");
            }
        }
    }

    // if we finally have a location, then compute country name and geo-coordinates
    if (location != null && location.length() > 0) {
        String location_country = map.has("location_country") ? (String) map.get("location_country") : null;
        String location_country_code = map.has("location_country_code")
                ? (String) map.get("location_country_code")
                : null;
        Object location_point = map.has("location_point") ? map.get("location_point") : null;
        Object location_mark = map.has("location") ? map.get("location") : null;
        // maybe we already computed these values before, but they may be incomplete. If they are not complete, we repeat the geocoding
        if (location_country == null || location_country.length() == 0 || location_country_code == null
                || location_country_code.length() == 0 || location_point == null || location_mark == null) {
            // get a salt 
            String created_at = map.has("created_at") ? (String) map.get("created_at") : null;
            int salt = created_at == null ? map.hashCode() : created_at.hashCode();
            // reverse geocode
            GeoMark loc = DAO.geoNames.analyse(location, null, 5, Integer.toString(salt));
            if (loc != null) {
                String countryCode = loc.getISO3166cc();
                if (countryCode != null && countryCode.length() > 0) {
                    String countryName = DAO.geoNames.getCountryName(countryCode);
                    map.put("location_country", countryName);
                    map.put("location_country_code", countryCode);
                }
                map.put("location_point", new double[] { loc.lon(), loc.lat() }); //[longitude, latitude]
                map.put("location_mark", new double[] { loc.mlon(), loc.mlat() }); //[longitude, latitude]
                //DAO.log("enrichLocation: FOUND   location '" + location + "'");
            } else {
                //DAO.log("enrichLocation: UNKNOWN location '" + location + "'");
            }
        }
    }

}

From source file:com.trk.aboutme.facebook.Response.java

private static Response createResponseFromObject(Request request, HttpURLConnection connection, Object object,
        boolean isFromCache, Object originalResult) throws JSONException {
    if (object instanceof JSONObject) {
        JSONObject jsonObject = (JSONObject) object;

        FacebookRequestError error = FacebookRequestError.checkResponseAndCreateError(jsonObject,
                originalResult, connection);
        if (error != null) {
            if (error.getErrorCode() == INVALID_SESSION_FACEBOOK_ERROR_CODE) {
                Session session = request.getSession();
                if (session != null) {
                    session.closeAndClearTokenInformation();
                }//from  www  .  ja  v a  2s  .  c om
            }
            return new Response(request, connection, error);
        }

        Object body = Utility.getStringPropertyAsJSON(jsonObject, BODY_KEY, NON_JSON_RESPONSE_PROPERTY);

        if (body instanceof JSONObject) {
            GraphObject graphObject = GraphObject.Factory.create((JSONObject) body);
            return new Response(request, connection, graphObject, isFromCache);
        } else if (body instanceof JSONArray) {
            GraphObjectList<GraphObject> graphObjectList = GraphObject.Factory.createList((JSONArray) body,
                    GraphObject.class);
            return new Response(request, connection, graphObjectList, isFromCache);
        }
        // We didn't get a body we understand how to handle, so pretend we got nothing.
        object = JSONObject.NULL;
    }

    if (object == JSONObject.NULL) {
        return new Response(request, connection, (GraphObject) null, isFromCache);
    } else {
        throw new FacebookException(
                "Got unexpected object type in response, class: " + object.getClass().getSimpleName());
    }
}

From source file:com.jsonstore.jackson.JsonOrgJSONObjectSerializer.java

protected void serializeContents(JSONObject value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonGenerationException {
    Iterator<?> i = value.keys();

    while (i.hasNext()) {
        String key = (String) i.next();
        Class<?> cls;// ww w.  jav a 2 s. com
        Object obj;

        try {
            obj = value.get(key);
        }

        catch (JSONException e) {
            throw new JsonGenerationException(e);
        }

        if ((obj == null) || (obj == JSONObject.NULL)) {
            jgen.writeNullField(key);

            continue;
        }

        jgen.writeFieldName(key);

        cls = obj.getClass();

        if ((cls == JSONObject.class) || JSONObject.class.isAssignableFrom(cls)) {
            serialize((JSONObject) obj, jgen, provider);
        }

        else if ((cls == JSONArray.class) || JSONArray.class.isAssignableFrom(cls)) {
            JsonOrgJSONArraySerializer.instance.serialize((JSONArray) obj, jgen, provider);
        }

        else if (cls == String.class) {
            jgen.writeString((String) obj);
        }

        else if (cls == Integer.class) {
            jgen.writeNumber(((Integer) obj).intValue());
        }

        else if (cls == Long.class) {
            jgen.writeNumber(((Long) obj).longValue());
        }

        else if (cls == Boolean.class) {
            jgen.writeBoolean(((Boolean) obj).booleanValue());
        }

        else if (cls == Double.class) {
            jgen.writeNumber(((Double) obj).doubleValue());
        }

        else {
            provider.defaultSerializeValue(obj, jgen);
        }
    }
}

From source file:io.github.grahambell.taco.ServerTest.java

@Test
public void testServerViaXP() throws TacoException {
    DummyTransport xp = (DummyTransport) this.xp;

    // We should be starting with an empty object cache.
    assertEquals(objects.size(), 0);//  w  ww. j a  v a  2  s .  co m
    assertEquals(objectNum, 0);

    // Try to construct a Date object.
    xp.setResponse(new JSONObject().put("action", "construct_object").put("class", "java.util.Date")
            .put("args", new JSONArray(new int[] { 115, 3, 1 })).put("kwargs", JSONObject.NULL), true);

    run();

    assertThat(xp.getMessage(), matchesJson(
            new JSONObject().put("action", "result").put("result", new JSONObject().put("_Taco_Object_", 1))));

    assertEquals(objects.size(), 1);
    assertEquals(objectNum, 1);
    assertTrue(objects.get(1) instanceof java.util.Date);

    // Try the Data object's methods.
    xp.setResponse(new JSONObject().put("action", "call_method").put("name", "getYear").put("number", 1)
            .put("args", JSONObject.NULL).put("kwargs", JSONObject.NULL), true);

    run();

    assertThat(xp.getMessage(), matchesJson(new JSONObject().put("action", "result").put("result", 115)));

    xp.setResponse(new JSONObject().put("action", "call_method").put("name", "getMonth").put("number", 1)
            .put("args", JSONObject.NULL).put("kwargs", JSONObject.NULL), true);

    run();

    assertThat(xp.getMessage(), matchesJson(new JSONObject().put("action", "result").put("result", 3)));

    xp.setResponse(new JSONObject().put("action", "call_method").put("name", "getDate").put("number", 1)
            .put("args", JSONObject.NULL).put("kwargs", JSONObject.NULL), true);

    run();

    assertThat(xp.getMessage(), matchesJson(new JSONObject().put("action", "result").put("result", 1)));

    // Construct a Locale object.
    xp.setResponse(
            new JSONObject().put("action", "construct_object").put("class", "java.util.Locale")
                    .put("args", new JSONArray(new String[] { "en", "US" })).put("kwargs", JSONObject.NULL),
            true);

    run();

    assertThat(xp.getMessage(), matchesJson(
            new JSONObject().put("action", "result").put("result", new JSONObject().put("_Taco_Object_", 2))));

    assertEquals(objects.size(), 2);
    assertEquals(objectNum, 2);
    assertTrue(objects.get(2) instanceof java.util.Locale);

    // Get a DateFormat object.
    xp.setResponse(
            new JSONObject().put("action", "call_class_method").put("class", "java.text.DateFormat")
                    .put("name", "getDateInstance")
                    .put("args",
                            new JSONArray(new Object[] { new Integer(DateFormat.SHORT),
                                    new JSONObject().put("_Taco_Object_", 2) }))
                    .put("kwargs", JSONObject.NULL),
            true);

    run();

    assertThat(xp.getMessage(), matchesJson(
            new JSONObject().put("action", "result").put("result", new JSONObject().put("_Taco_Object_", 3))));

    assertEquals(objects.size(), 3);
    assertEquals(objectNum, 3);
    assertTrue(objects.get(3) instanceof java.text.DateFormat);

    // Finally, format the date.
    xp.setResponse(new JSONObject().put("action", "call_method").put("number", 3).put("name", "format")
            .put("args", new JSONArray(new Object[] { new JSONObject().put("_Taco_Object_", 1) }))
            .put("kwargs", JSONObject.NULL), true);

    run();

    assertThat(xp.getMessage(), matchesJson(new JSONObject().put("action", "result").put("result", "4/1/15")));

    // Destroy the objects.
    xp.setResponse(new JSONObject().put("action", "destroy_object").put("number", 3), true);

    run();

    assertEquals(objects.size(), 2);

    xp.setResponse(new JSONObject().put("action", "destroy_object").put("number", 2), true);

    run();

    assertEquals(objects.size(), 1);
    assertTrue(objects.get(1) instanceof java.util.Date);

    xp.setResponse(new JSONObject().put("action", "destroy_object").put("number", 1), true);

    run();

    assertEquals(objects.size(), 0);

    // Counter should not have been reset.
    assertEquals(objectNum, 3);

    xp.setResponse(new JSONObject().put("action", "construct_object").put("class", "java.util.Date")
            .put("args", JSONObject.NULL).put("kwargs", JSONObject.NULL), true);

    run();

    assertThat(xp.getMessage(), matchesJson(
            new JSONObject().put("action", "result").put("result", new JSONObject().put("_Taco_Object_", 4))));

    assertEquals(objectNum, 4);
    assertEquals(objects.size(), 1);

    // Test class attribute actions.
    xp.setResponse(new JSONObject().put("action", "get_class_attribute")
            .put("class", "io.github.grahambell.taco.ExampleClass").put("name", "attr_one"), true);

    run();

    assertThat(xp.getMessage(), matchesJson(new JSONObject().put("action", "result").put("result", 5678)));

    xp.setResponse(new JSONObject().put("action", "set_class_attribute")
            .put("class", "io.github.grahambell.taco.ExampleClass").put("name", "attr_one").put("value", 8765),
            true);

    run();

    assertThat(xp.getMessage(),
            matchesJson(new JSONObject().put("action", "result").put("result", JSONObject.NULL)));

    assertEquals(8765, ExampleClass.attr_one);
}