Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:io.crate.frameworks.mesos.api.CrateRestResource.java

@Nullable
String mesosMasterAddress() {// www .j a  va  2  s  . co m
    try (CuratorFramework cf = zkClient()) {
        cf.start();
        List<String> children = cf.getChildren().forPath("/mesos");
        List<Integer> masterIds = new ArrayList<Integer>();
        if (children.isEmpty()) {
            return null;
        }
        JSONObject cfData = null;

        for (String child : children) {
            if (child.startsWith("json.info")) {
                masterIds.add(Integer.parseInt(child.split("_")[1]));
            }
        }
        Collections.sort(masterIds);
        for (String child : children) {
            if (child.endsWith(String.valueOf(masterIds.get(0)))) {
                cfData = new JSONObject(new String(cf.getData().forPath("/mesos/" + child)));
                break;
            }
        }

        if (cfData != null) {
            JSONObject address = cfData.getJSONObject("address");
            return String.format("%s:%d", address.getString("ip"), address.getInt("port"));
        }
    } catch (Exception e) {
        LOGGER.error("Error while obtaining a mesos address from the curator framework: ", e);
    }
    return null;
}

From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java

/**
 * Basing on passed profileInfo, creates object of type BackendCapability.
 * /*  w  ww . j a v a 2  s  .  co  m*/
 * @param profileInfo Profile described in JSOSObject.
 * @return Object of BackendCapability derived from passed profileInfo.
 */
private BackendCapability createBackedCapability(JSONObject profileInfo) {

    /*
     * determine value of name parameter to be used with BackendCapability 
     */
    String profileName = profileInfo.getString(JSON_KEY_NAME);

    /*
     * determine value of type attribute to be used with BackendCapability
     */
    BackendCapability.CapabilityType type = null;
    String typeAsString = profileInfo.getString(JSON_KEY_TYPE);
    switch (typeAsString) {
    case CDMI_OBJECT_TYPE_CONTAINER:
        type = BackendCapability.CapabilityType.CONTAINER;
        break;
    case CDMI_OBJECT_TYPE_DATAOBJECT:
        type = BackendCapability.CapabilityType.DATAOBJECT;
        break;
    default:
        throw new RuntimeException("Unknown capability type");
    }

    /*
     * create new instance of BackendCapability 
     * (it is empty for now, the metadata and capabilities properties have to be created, 
     * populated and passed to the BackendCapability object)
     */
    final BackendCapability returnBackendCapability = new BackendCapability(profileName, type);

    /*
     * create capabilities object (to be populated and injected into returned BackendCapability)
     */
    Map<String, Object> capabilities = new HashMap<>();

    /*
     * Add always present capabilities
     */
    capabilities.put("cdmi_capabilities_templates", "true");
    capabilities.put("cdmi_capabilities_exact_inherit", "true");

    /*
     * create metadata object (to be populated and injected into returned BackendCapability)
     */
    Map<String, Object> metadata = new HashMap<>();

    /*
     * iterate through metadata in profileInfo and populate capabilities and 
     * metadata in BackendCapability object
     */
    JSONObject metadataObj = profileInfo.getJSONObject(JSON_KEY_METADATA);

    log.debug("Processing metadata array from profile returned by BackendGateway");

    Iterator<?> keys = metadataObj.keys();
    while (keys.hasNext()) {

        /*
         * get key name for current item in metadata array
         */
        String key = (String) keys.next();

        /*
         * get value assigned to the current key, and convert the value to String
         * NOTE: The convention is required because returned value can be for example of array type 
         * or of another JSONObject, it not necessary has to be String, so usage of 
         * metadataObj.getString(key) would be wrong 
         */
        Object valueObj = metadataObj.get(key);

        log.debug("Current metadata key: {}", key);
        log.debug("Current metadata value: {}", valueObj);
        log.debug("Metadata value class/type is: {}", valueObj.getClass());

        /*
         * Create key and value to be added to capabilities.
         * Separate variables for key and value objects are introduced deliberately 
         * to note that in future or in case of any special values, an additional 
         * logic / calculation can be required to obtain key and value to be used 
         * with capabilities map 
         */
        String cdmiCapabilityKey = key;
        String cdmiCapabilityValue = "true";

        /*
         * add "calculated" key and value to the capabilities map
         */
        capabilities.put(cdmiCapabilityKey, cdmiCapabilityValue);

        /*
         * see above comments for capabilities related keys and values
         */
        String cdmiMetadataKey = key;
        Object cdmiMetadataValue = valueObj;

        /*
         * add "calculated" key and value to the metadata map
         */
        metadata.put(cdmiMetadataKey, cdmiMetadataValue);

    } // while()

    //capabilities.put("cdmi_capabilities_allowed", "true");

    /*
     * process allowed profiles
     */
    try {

        JSONArray allowedProfiles = profileInfo.getJSONArray(JSON_KEY_ALLOWED_PROFILES);
        String profilesUris = profilesToUris(allowedProfiles, retriveObjectTypeAsString(profileInfo));
        log.debug("allowedProfiles: {}", allowedProfiles);
        log.debug("profilesURIs: {}", profilesUris);

        metadata.put("cdmi_capabilities_allowed", profilesUris);

    } catch (JSONException ex) {

        log.debug("No {} key in processed JSON document", JSON_KEY_ALLOWED_PROFILES);

    } // try{}

    returnBackendCapability.setCapabilities(capabilities);
    returnBackendCapability.setMetadata(metadata);

    return returnBackendCapability;

}

From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java

/**
 * Basing on passed JSON in String format, creates object of CdmiObjecStatus.
 * (Translates JSON in String format into CdmiObjectStatus)
 *//*  w w  w.  j  av  a 2  s.  c o  m*/
@Override
public CdmiObjectStatus getCdmiObjectStatus(String gatewayResponse) {

    //log.debug("Translate {} to CdmiObjectStatus", gatewayResponse);

    Map<String, Object> monitoredAttributes = new HashMap<>();

    JSONObject profile = new JSONObject(gatewayResponse);
    //log.debug("profile: {}", profile);

    JSONObject metadataProvided = profile.getJSONObject("metadata_provided");
    //log.debug("metadata_provided: {}", metadataProvided);

    Iterator<?> keys = metadataProvided.keys();
    while (keys.hasNext()) {

        /*
         * get key name for current item in metadata array
         */
        String key = (String) keys.next();
        //log.debug("key: {}", key);

        Object metadataProvidedAsObj = metadataProvided.get(key);
        //String metadataProvidedAsString = metadataProvidedAsObj.toString();

        //monitoredAttributes.put(key, metadataProvidedAsString);
        monitoredAttributes.put(key, metadataProvidedAsObj);

    }

    String profileName = profile.getString("name");
    String type = profile.getString("type");

    String currentCapabilitiesUri = "/cdmi_capabilities/" + type + "/" + profileName;

    return new CdmiObjectStatus(monitoredAttributes, currentCapabilitiesUri, null);

}

From source file:com.flurry.samples.tumblrsharing.PhotoFeedActivity.java

/**
 * Method to display photo feed./* w ww .j  a  v a2  s  . c  o m*/
 * */
private void fetchPhotoFeed() {
    flickrClient = new FlickrClient();

    HashMap<String, String> fetchPhotosEventParams = new HashMap<>(1);
    fetchPhotosEventParams.put(AnalyticsHelper.PARAM_LOCATION, String.valueOf(lastLocation));
    AnalyticsHelper.logEvent(AnalyticsHelper.EVENT_FETCH_PHOTOS, fetchPhotosEventParams, true);

    flickrClient.getPhotoFeed(lastLocation, new JsonHttpResponseHandler() {

        @Override
        public void onSuccess(int code, Header[] headers, JSONObject body) {

            AnalyticsHelper.endTimedEvent(AnalyticsHelper.EVENT_FETCH_PHOTOS);

            JSONObject photosObject = null;
            if (body != null) {
                try {
                    if (body.has("photos")) {
                        photosObject = body.getJSONObject("photos");
                        JSONArray photoArray = photosObject.getJSONArray("photo");
                        List<Photo> photosList = Photo.fromJson(photoArray);
                        photoAdapter.addPhotos(photosList);
                        photoAdapter.notifyDataSetChanged();
                    } else {
                        Toast.makeText(getApplicationContext(), "Flickr Api error.", Toast.LENGTH_LONG).show();
                        finish();
                    }
                } catch (JSONException e) {
                    AnalyticsHelper.logError(LOG_TAG, "Photo Feed JSON Error", e);
                }
            } else {
                Toast.makeText(getApplicationContext(), "Flickr Api error.", Toast.LENGTH_LONG).show();
                AnalyticsHelper.logError(LOG_TAG, "Response body is null", null);
                finish();
            }

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            Toast.makeText(getApplicationContext(), "Flickr Api error.", Toast.LENGTH_LONG).show();
            AnalyticsHelper.logError(LOG_TAG, "Failure in fetching photo feed", null);
            finish();
        }
    });
}

From source file:net.dv8tion.jda.core.handle.MessageUpdateHandler.java

private Long handleDefaultMessage(JSONObject content) {
    Message message;//from w w w  .  j a va2 s.c o m
    try {
        message = api.getEntityBuilder().createMessage(content);
    } catch (IllegalArgumentException e) {
        switch (e.getMessage()) {
        case EntityBuilder.MISSING_CHANNEL: {
            final long channelId = content.getLong("channel_id");
            api.getEventCache().cache(EventCache.Type.CHANNEL, channelId,
                    () -> handle(responseNumber, allContent));
            EventCache.LOG
                    .debug("Received a message update for a channel that JDA does not currently have cached");
            return null;
        }
        case EntityBuilder.MISSING_USER: {
            final long authorId = content.getJSONObject("author").getLong("id");
            api.getEventCache().cache(EventCache.Type.USER, authorId, () -> handle(responseNumber, allContent));
            EventCache.LOG
                    .debug("Received a message update for a user that JDA does not currently have cached");
            return null;
        }
        default:
            throw e;
        }
    }

    switch (message.getChannelType()) {
    case TEXT: {
        TextChannel channel = message.getTextChannel();
        if (api.getGuildLock().isLocked(channel.getGuild().getIdLong())) {
            return channel.getGuild().getIdLong();
        }
        api.getEventManager().handle(new GuildMessageUpdateEvent(api, responseNumber, message));
        break;
    }
    case PRIVATE: {
        api.getEventManager().handle(new PrivateMessageUpdateEvent(api, responseNumber, message));
    }
    case GROUP: {
        api.getEventManager().handle(new GroupMessageUpdateEvent(api, responseNumber, message));
        break;
    }

    default:
        WebSocketClient.LOG
                .warn("Received a MESSAGE_UPDATE with a unknown MessageChannel ChannelType. JSON: " + content);
        return null;
    }

    //Combo event
    api.getEventManager().handle(new MessageUpdateEvent(api, responseNumber, message));
    return null;
}

From source file:com.mobile.system.db.abatis.AbatisService.java

/**
 * //  w w  w  .  ja v  a2s.c o m
 * @param jsonStr
 *            JSON String
 * @param beanClass
 *            Bean class
 * @param basePackage
 *            Base package name which includes all Bean classes
 * @return Object Bean
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception {
    Object obj = null;
    JSONObject jsonObj = new JSONObject(jsonStr);
    // Check bean object
    if (beanClass == null) {
        Log.d(TAG, "Bean class is null");
        return null;
    }
    // Read Class member fields
    Field[] props = beanClass.getDeclaredFields();
    if (props == null || props.length == 0) {
        Log.d(TAG, "Class" + beanClass.getName() + " has no fields");
        return null;
    }
    // Create instance of this Bean class
    obj = beanClass.newInstance();
    // Set value of each member variable of this object
    for (int i = 0; i < props.length; i++) {
        String fieldName = props[i].getName();
        // Skip public and static fields
        if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) {
            continue;
        }
        // Date Type of Field
        Class type = props[i].getType();
        String typeName = type.getName();
        // Check for Custom type
        if (typeName.equals("int")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getInt(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("long")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getLong(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.lang.String")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getString(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("double")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getDouble(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.util.Date")) { // modify

            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);

            String dateString = jsonObj.getString(fieldName);
            dateString = dateString.replace(" KST", "");
            SimpleDateFormat genderFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.KOREA);
            // Set value
            try {
                Date afterDate = genderFormat.parse(dateString);
                m.invoke(obj, afterDate);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        } else if (type.getName().equals(List.class.getName())
                || type.getName().equals(ArrayList.class.getName())) {
            // Find out the Generic
            String generic = props[i].getGenericType().toString();
            if (generic.indexOf("<") != -1) {
                String genericType = generic.substring(generic.lastIndexOf("<") + 1, generic.lastIndexOf(">"));
                if (genericType != null) {
                    JSONArray array = null;
                    try {
                        array = jsonObj.getJSONArray(fieldName);
                    } catch (Exception ex) {
                        Log.d(TAG, ex.getMessage());
                        array = null;
                    }
                    if (array == null) {
                        continue;
                    }
                    ArrayList arrayList = new ArrayList();
                    for (int j = 0; j < array.length(); j++) {
                        arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType),
                                basePackage));
                    }
                    // Set value
                    Class[] parms = { type };
                    Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                    m.setAccessible(true);
                    m.invoke(obj, arrayList);
                }
            } else {
                // No generic defined
                generic = null;
            }
        } else if (typeName.startsWith(basePackage)) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                JSONObject customObj = jsonObj.getJSONObject(fieldName);
                if (customObj != null) {
                    m.invoke(obj, parse(customObj.toString(), type, basePackage));
                }
            } catch (JSONException ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else {
            // Skip
            Log.d(TAG, "Field " + fieldName + "#" + typeName + " is skip");
        }
    }
    return obj;
}

From source file:net.wedjaa.elasticparser.tester.ESSearchTester.java

private static int countIndexed() {
    System.out.println("Getting the indexing status");
    int indexed = 0;

    HttpGet statusGet = new HttpGet("http://localhost:9500/unit/_stats");
    try {//  www  .  j a  v a 2s.c o m
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        System.out.println("Executing request");
        HttpResponse response = httpclient.execute(statusGet);
        System.out.println("Processing response");
        InputStream isResponse = response.getEntity().getContent();
        BufferedReader isReader = new BufferedReader(new InputStreamReader(isResponse));
        StringBuilder strBuilder = new StringBuilder();
        String readLine;
        while ((readLine = isReader.readLine()) != null) {
            strBuilder.append(readLine);
        }
        isReader.close();
        System.out.println("Done - reading JSON");
        JSONObject esResponse = new JSONObject(strBuilder.toString());
        indexed = esResponse.getJSONObject("indices").getJSONObject("unit").getJSONObject("total")
                .getJSONObject("docs").getInt("count");
        System.out.println("Indexed docs: " + indexed);
        httpclient.close();
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    return indexed;
}

From source file:com.nginious.http.serialize.JsonSerializerTestCase.java

public void testJsonSerializer() throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
    SerializableBean bean = new SerializableBean();
    bean.setBooleanValue(true);/*  w  w  w .j  av  a 2s .c o  m*/
    bean.setDoubleValue(0.451);
    bean.setFloatValue(1.34f);
    bean.setIntValue(3400100);
    bean.setLongValue(3400100200L);
    bean.setShortValue((short) 32767);
    bean.setStringValue("String");
    bean.setDateValue(format.parse("2011-08-24T08:50:23+0200"));
    Date calDate = format.parse("2011-08-24T08:52:23+0200");
    Calendar cal = Calendar.getInstance();
    cal.setTime(calDate);
    bean.setCalendarValue(cal);
    bean.setObjectValue(TimeZone.getDefault());

    InBean inBean = new InBean();
    inBean.setFirst(true);
    inBean.setSecond(0.567d);
    inBean.setThird(0.342f);
    inBean.setFourth(100);
    inBean.setFifth(3400200100L);
    inBean.setSixth((short) 32767);
    inBean.setSeventh("String");
    inBean.setEight(format.parse("2011-08-25T08:50:23+0200"));
    cal = Calendar.getInstance();
    calDate = format.parse("2011-08-25T08:52:23+0200");
    cal.setTime(calDate);
    inBean.setNinth(cal);
    bean.setBeanValue(inBean);

    List<InBean> beanList = new ArrayList<InBean>();
    beanList.add(inBean);
    beanList.add(inBean);
    bean.setBeanListValue(beanList);

    List<String> stringList = new ArrayList<String>();
    stringList.add("One");
    stringList.add("Two");
    stringList.add("Three");
    bean.setStringListValue(stringList);

    ApplicationClassLoader classLoader = new ApplicationClassLoader(
            Thread.currentThread().getContextClassLoader());
    SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader);
    Serializer<SerializableBean> serializer = serializerFactory.createSerializer(SerializableBean.class,
            "application/json");
    assertEquals("application/json", serializer.getMimeType());

    StringWriter strWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(strWriter);

    serializer.serialize(writer, bean);
    writer.flush();
    JSONObject json = new JSONObject(strWriter.toString());
    assertNotNull(json);
    assertTrue(json.has("serializableBean"));
    json = json.getJSONObject("serializableBean");

    assertEquals(true, json.getBoolean("booleanValue"));
    assertEquals(0.451, json.getDouble("doubleValue"));
    assertEquals(1.34f, (float) json.getDouble("floatValue"));
    assertEquals(3400100, json.getInt("intValue"));
    assertEquals(3400100200L, json.getLong("longValue"));
    assertEquals(32767, (short) json.getInt("shortValue"));
    assertEquals("String", json.getString("stringValue"));
    assertEquals("2011-08-24T08:50:23+02:00", json.getString("dateValue"));
    assertEquals("2011-08-24T08:52:23+02:00", json.getString("calendarValue"));
    assertEquals(TimeZone.getDefault().toString(), json.getString("objectValue"));

    assertTrue(json.has("beanValue"));
    JSONObject inBeanJson = json.getJSONObject("beanValue");
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    assertTrue(json.has("stringListValue"));
    JSONArray stringListJson = json.getJSONArray("stringListValue");
    assertEquals("One", stringListJson.get(0));
    assertEquals("Two", stringListJson.get(1));
    assertEquals("Three", stringListJson.get(2));

    assertTrue(json.has("beanListValue"));
    JSONArray beanListJson = json.getJSONArray("beanListValue");

    inBeanJson = beanListJson.getJSONObject(0);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    inBeanJson = beanListJson.getJSONObject(1);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));
}

From source file:com.nginious.http.serialize.JsonSerializerTestCase.java

public void testNamedJsonSerializer() throws Exception {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
    NamedBean bean = new NamedBean();
    bean.setBooleanValue(true);//from  w  ww.j  a va 2s.  co  m
    bean.setDoubleValue(0.451);
    bean.setFloatValue(1.34f);
    bean.setIntValue(3400100);
    bean.setLongValue(3400100200L);
    bean.setShortValue((short) 32767);
    bean.setStringValue("String");
    bean.setDateValue(format.parse("2011-08-24T08:50:23+0200"));
    Date calDate = format.parse("2011-08-24T08:52:23+0200");
    Calendar cal = Calendar.getInstance();
    cal.setTime(calDate);
    bean.setCalendarValue(cal);
    bean.setObjectValue(TimeZone.getDefault());

    InBean inBean = new InBean();
    inBean.setFirst(true);
    inBean.setSecond(0.567d);
    inBean.setThird(0.342f);
    inBean.setFourth(100);
    inBean.setFifth(3400200100L);
    inBean.setSixth((short) 32767);
    inBean.setSeventh("String");
    inBean.setEight(format.parse("2011-08-25T08:50:23+0200"));
    cal = Calendar.getInstance();
    calDate = format.parse("2011-08-25T08:52:23+0200");
    cal.setTime(calDate);
    inBean.setNinth(cal);
    bean.setBeanValue(inBean);

    List<InBean> beanList = new ArrayList<InBean>();
    beanList.add(inBean);
    beanList.add(inBean);
    bean.setBeanListValue(beanList);

    List<String> stringList = new ArrayList<String>();
    stringList.add("One");
    stringList.add("Two");
    stringList.add("Three");
    bean.setStringListValue(stringList);

    ApplicationClassLoader classLoader = new ApplicationClassLoader(
            Thread.currentThread().getContextClassLoader());
    SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader);
    Serializer<NamedBean> serializer = serializerFactory.createSerializer(NamedBean.class, "application/json");
    assertEquals("application/json", serializer.getMimeType());

    StringWriter strWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(strWriter);

    serializer.serialize(writer, bean);
    writer.flush();
    JSONObject json = new JSONObject(strWriter.toString());
    assertNotNull(json);
    assertTrue(json.has("testNamedBean"));
    json = json.getJSONObject("testNamedBean");

    assertEquals(true, json.getBoolean("testBooleanValue"));
    assertEquals(0.451, json.getDouble("testDoubleValue"));
    assertEquals(1.34f, (float) json.getDouble("testFloatValue"));
    assertEquals(3400100, json.getInt("testIntValue"));
    assertEquals(3400100200L, json.getLong("testLongValue"));
    assertEquals(32767, (short) json.getInt("testShortValue"));
    assertEquals("String", json.getString("testStringValue"));
    assertEquals("2011-08-24T08:50:23+02:00", json.getString("testDateValue"));
    assertEquals("2011-08-24T08:52:23+02:00", json.getString("testCalendarValue"));
    assertEquals(TimeZone.getDefault().toString(), json.getString("testObjectValue"));

    assertTrue(json.has("testBeanValue"));
    JSONObject inBeanJson = json.getJSONObject("testBeanValue");
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    assertTrue(json.has("testStringListValue"));
    JSONArray stringListJson = json.getJSONArray("testStringListValue");
    assertEquals("One", stringListJson.get(0));
    assertEquals("Two", stringListJson.get(1));
    assertEquals("Three", stringListJson.get(2));

    assertTrue(json.has("testBeanListValue"));
    JSONArray beanListJson = json.getJSONArray("testBeanListValue");

    inBeanJson = beanListJson.getJSONObject(0);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));

    inBeanJson = beanListJson.getJSONObject(1);
    assertTrue(inBeanJson.has("inBean"));
    inBeanJson = inBeanJson.getJSONObject("inBean");
    assertEquals(true, inBeanJson.getBoolean("first"));
    assertEquals(0.567, inBeanJson.getDouble("second"));
    assertEquals(0.342f, (float) inBeanJson.getDouble("third"));
    assertEquals(100, inBeanJson.getInt("fourth"));
    assertEquals(3400200100L, inBeanJson.getLong("fifth"));
    assertEquals(32767, (short) inBeanJson.getInt("sixth"));
    assertEquals("String", inBeanJson.getString("seventh"));
    assertEquals("2011-08-25T08:50:23+02:00", inBeanJson.getString("eight"));
    assertEquals("2011-08-25T08:52:23+02:00", inBeanJson.getString("ninth"));
}

From source file:com.nginious.http.serialize.JsonSerializerTestCase.java

public void testEmptyJsonSerializer() throws Exception {
    SerializableBean bean = new SerializableBean();
    ApplicationClassLoader classLoader = new ApplicationClassLoader(
            Thread.currentThread().getContextClassLoader());
    SerializerFactoryImpl serializerFactory = new SerializerFactoryImpl(classLoader);
    Serializer<SerializableBean> serializer = serializerFactory.createSerializer(SerializableBean.class,
            "application/json");
    assertEquals("application/json", serializer.getMimeType());

    StringWriter strWriter = new StringWriter();
    PrintWriter writer = new PrintWriter(strWriter);
    serializer.serialize(writer, bean);/*  ww w  . j  a va 2  s  . com*/
    writer.flush();
    JSONObject json = new JSONObject(strWriter.toString());
    assertNotNull(json);
    assertTrue(json.has("serializableBean"));
    json = json.getJSONObject("serializableBean");

    assertEquals(false, json.getBoolean("booleanValue"));
    assertEquals(0.0d, json.getDouble("doubleValue"));
    assertEquals(0.0f, (float) json.getDouble("floatValue"));
    assertEquals(0, json.getInt("intValue"));
    assertEquals(0L, json.getLong("longValue"));
    assertEquals(0, (short) json.getInt("shortValue"));
    assertFalse(json.has("stringValue"));
    assertFalse(json.has("dateValue"));
    assertFalse(json.has("calendarValue"));
    assertFalse(json.has("objectValue"));
}