Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray(Object array) throws JSONException 

Source Link

Document

Construct a JSONArray from an array

Usage

From source file:cz.muni.fi.japanesedictionary.entity.JapaneseCharacter.java

/**
 * Takes json string and parses it to list of dutch meanings.
 * /*  w w  w.  java 2  s  .co m*/
 * @param jsonString - JSON string to be parsed
 */
public void parseMeaningDutch(String jsonString) {
    if (jsonString == null || jsonString.length() < 1) {
        return;
    }
    List<String> temp;
    JSONArray parseJSON;
    try {
        parseJSON = new JSONArray(jsonString);
    } catch (JSONException e) {
        Log.w(LOG_TAG, "parsing parseMeaningDutch() - initial expression failed: " + e.toString());
        return;
    }
    temp = this.parseOneJSONArray(parseJSON);
    for (String str : temp) {
        this.addMeaningDutch(str);
    }
}

From source file:cz.muni.fi.japanesedictionary.entity.JapaneseCharacter.java

/**
 * Takes json string and parses it to list of german meanings.
 * /* w  ww.  j  a  v a2s.  com*/
 * @param jsonString - JSON string to be parsed
 */
public void parseMeaningGerman(String jsonString) {
    if (jsonString == null || jsonString.length() < 1) {
        return;
    }
    List<String> temp;
    JSONArray parseJSON;
    try {
        parseJSON = new JSONArray(jsonString);
    } catch (JSONException e) {
        Log.w(LOG_TAG, "parsing parseMeaningGerman() - initial expression failed: " + e.toString());
        return;
    }
    temp = this.parseOneJSONArray(parseJSON);
    for (String str : temp) {
        this.addMeaningGerman(str);
    }
}

From source file:cz.muni.fi.japanesedictionary.entity.JapaneseCharacter.java

/**
 * Takes json string and parses it to list of russian meanings.
 *
 * @param jsonString - JSON string to be parsed
 *//*from  ww w . j a  v  a2 s.  c  o  m*/
public void parseMeaningRussian(String jsonString) {
    if (jsonString == null || jsonString.length() < 1) {
        return;
    }
    List<String> temp;
    JSONArray parseJSON;
    try {
        parseJSON = new JSONArray(jsonString);
    } catch (JSONException e) {
        Log.w(LOG_TAG, "parsing parseMeaningRussian() - initial expression failed: " + e.toString());
        return;
    }
    temp = this.parseOneJSONArray(parseJSON);
    for (String str : temp) {
        this.addMeaningRussian(str);
    }
}

From source file:cz.muni.fi.japanesedictionary.entity.JapaneseCharacter.java

/**
 * Takes json string and parses it to list of nanori.
 * /*  w ww .  ja v  a  2  s  .c  o m*/
 * @param jsonString - JSON string to be parsed
 */
public void parseNanori(String jsonString) {
    if (jsonString == null || jsonString.length() < 1) {
        return;
    }
    List<String> temp;
    JSONArray parseJSON;
    try {
        parseJSON = new JSONArray(jsonString);
    } catch (JSONException e) {
        Log.w(LOG_TAG, "parsing parseNanori() - initial expression failed: " + e.toString());
        return;
    }
    temp = this.parseOneJSONArray(parseJSON);
    for (String str : temp) {
        this.addNanori(str);
    }
}

From source file:cz.muni.fi.japanesedictionary.entity.JapaneseCharacter.java

/**
 *   Adds JapaneseCharater to given bundle.
 * /*from  w w w . j  a va  2 s. c o m*/
 * @param bundle - bundle in which character should be saved
 *              - in case of null empty bundle is created
 * @return Bundle returns bundle which contains CharacterInfo
 */
public Bundle createBundleFromJapaneseCharacter(Bundle bundle) {
    if (bundle == null) {
        bundle = new Bundle();
    }
    if (this.getLiteral() != null && this.getLiteral().length() > 0) {
        bundle.putString(SAVE_CHARACTER_LITERAL, this.getLiteral());
    }
    if (this.getRadicalClassic() != 0) {
        bundle.putInt(SAVE_CHARACTER_RADICAL, this.getRadicalClassic());
    }
    if (this.getGrade() != 0) {
        bundle.putInt(SAVE_CHARACTER_GRADE, this.getGrade());
    }
    if (this.getStrokeCount() != 0) {
        bundle.putInt(SAVE_CHARACTER_STROKE_COUNT, this.getStrokeCount());
    }
    if (this.getSkip() != null && this.getSkip().length() > 0) {
        bundle.putString(SAVE_CHARACTER_SKIP, this.getSkip());
    }
    if (this.getDicRef() != null && this.getDicRef().size() > 0) {
        bundle.putString(SAVE_CHARACTER_DIC_REF, (new JSONObject(this.getDicRef()).toString()));
    }
    if (this.getRmGroupJaOn() != null && this.getRmGroupJaOn().size() > 0) {
        bundle.putString(SAVE_CHARACTER_JA_ON, (new JSONArray(this.getRmGroupJaOn())).toString());
    }
    if (this.getRmGroupJaKun() != null && this.getRmGroupJaKun().size() > 0) {
        bundle.putString(SAVE_CHARACTER_JA_KUN, (new JSONArray(this.getRmGroupJaKun())).toString());
    }
    if (this.getMeaningEnglish() != null && this.getMeaningEnglish().size() > 0) {
        bundle.putString(SAVE_CHARACTER_ENGLISH, (new JSONArray(this.getMeaningEnglish())).toString());
    }
    if (this.getMeaningFrench() != null && this.getMeaningFrench().size() > 0) {
        bundle.putString(SAVE_CHARACTER_FRENCH, (new JSONArray(this.getMeaningFrench())).toString());
    }
    if (this.getMeaningDutch() != null && this.getMeaningDutch().size() > 0) {
        bundle.putString(SAVE_CHARACTER_DUTCH, (new JSONArray(this.getMeaningDutch())).toString());
    }
    if (this.getMeaningGerman() != null && this.getMeaningGerman().size() > 0) {
        bundle.putString(SAVE_CHARACTER_GERMAN, (new JSONArray(this.getMeaningGerman())).toString());
    }
    if (this.getMeaningRussian() != null && this.getMeaningRussian().size() > 0) {
        bundle.putString(SAVE_CHARACTER_RUSSIAN, (new JSONArray(this.getMeaningRussian())).toString());
    }
    if (this.getNanori() != null && this.getNanori().size() > 0) {
        bundle.putString(SAVE_CHARACTER_NANORI, (new JSONArray(this.getNanori())).toString());
    }

    return bundle;
}

From source file:name.wildswift.android.libs.server.json.JsonDomRequest.java

/**
 * Callback to work with response. Called when input from server gets, and return result of request.<br/>
 * Load all server data. Parse JSON and call one of convert methods.
 * Don't override. If need, use {@link  name.wildswift.android.libs.server.ServerRequest} instead
 *
 * @param content input from server side
 * @return result of processing request (data object or other information)
 * @throws name.wildswift.android.libs.exceptions.ServerApiException
 *                             if error in server format of data
 * @throws java.io.IOException if IOErrors occurred
 */// w w  w  . j a  va  2  s  . c  o  m
@Override
public final T processRequest(InputStream content) throws ServerApiException, IOException {
    ByteArrayOutputStream dataCache = new ByteArrayOutputStream();

    // Fully read data
    byte[] buff = new byte[1024];
    int len;
    while ((len = content.read(buff)) >= 0) {
        dataCache.write(buff, 0, len);
    }

    // Close streams
    dataCache.close();

    String jsonString = new String(dataCache.toByteArray()).trim();

    // Check for array index out of bounds
    if (jsonString.length() > 0) {
        try {
            // switch type of Json root object
            if (jsonString.startsWith("{")) {
                return convertJson(new JSONObject(jsonString));
            } else {
                return convertJson(new JSONArray(jsonString));
            }
        } catch (JSONException e) {
            // Box exception
            throw new ServerApiException(e);
        }
    }
    throw new ServerApiException("No data returned");
}

From source file:com.hueemulator.lighting.utils.TestUtils.java

/**
 * Tests two JSON strings for equality by performing a deep comparison.
 *
 * @param json1 represents a JSON object to compare with json2
 * @param json2 represents a JSON object to compare with json1
 * @return true if the JSON objects are equal, false otherwise
 *//*from w w  w.j  ava 2 s .  c o  m*/
public static boolean jsonsArrayEqual(String json1, String json2) throws Exception {
    Object obj1Converted = convertJsonElement(new JSONArray(json1));
    Object obj2Converted = convertJsonElement(new JSONArray(json2));
    return obj1Converted.equals(obj2Converted);
}

From source file:org.acaro.graffiti.processing.GraffitiReader.java

@Override
public BasicVertex<Text, IntWritable, Text, Message> getCurrentVertex()
        throws IOException, InterruptedException {

    Vertex vertex = new Vertex();
    Text line = getRecordReader().getCurrentValue();

    try {/* w w w  .j a v a 2 s .  c  o  m*/

        JSONArray jsonVertex = new JSONArray(line.toString());
        vertex.setVertexId(new Text(jsonVertex.getString(0)));
        vertex.setMsgList(msgList);
        JSONArray jsonEdgeArray = jsonVertex.getJSONArray(1);

        for (int i = 0; i < jsonEdgeArray.length(); ++i) {
            JSONArray jsonEdge = jsonEdgeArray.getJSONArray(i);
            vertex.addEdge(new Text(jsonEdge.getString(1)), new Text(jsonEdge.getString(0)));
        }
    } catch (JSONException e) {
        throw new IllegalArgumentException("next: Couldn't get vertex from line " + line, e);
    }

    return vertex;
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *//*from w  w  w. j  a v a 2  s  .  c o m*/
public String getRemoteLoyaltyCards() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                LoyaltyCard.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SYNC_MESSAGE,
                                "Reading loyalty cards on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject loyaltyCardJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        LoyaltyCard loyaltyCard = LoyaltyCard
                                .getByRemoteId(loyaltyCardJson.get("_id").toString());
                        if (loyaltyCard == null) {
                            loyaltyCard = new LoyaltyCard(loyaltyCardJson);
                        } else {
                            loyaltyCard.setRemoteId(loyaltyCardJson.getString("_id"));
                            loyaltyCard.setRawValue(loyaltyCardJson.getString("rawValue"));
                            loyaltyCard.setCode(loyaltyCardJson.getInt("code"));
                            loyaltyCard.setLabel(loyaltyCardJson.getString("label"));
                            loyaltyCard.setCreationDate(loyaltyCardJson.getString("creationDate"));
                        }

                        loyaltyCard.save();
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:org.vaadin.addons.locationtextfield.OpenStreetMapGeocoder.java

protected Collection<GeocodedLocation> createLocations(String address, String input) throws GeocodingException {
    final Set<GeocodedLocation> locations = new LinkedHashSet<GeocodedLocation>();
    try {/* ww w. j  a  v  a  2s.  co  m*/
        JSONArray results = new JSONArray(input);
        boolean ambiguous = results.length() > 1;
        for (int i = 0; i < results.length(); i++) {
            JSONObject result = results.getJSONObject(i);
            GeocodedLocation loc = new GeocodedLocation();
            loc.setAmbiguous(ambiguous);
            loc.setOriginalAddress(address);
            loc.setGeocodedAddress(result.getString("display_name"));
            loc.setLat(Double.parseDouble(result.getString("lat")));
            loc.setLon(Double.parseDouble(result.getString("lon")));
            loc.setType(getLocationType(result));
            if (result.has("address")) {
                JSONObject obj = result.getJSONObject("address");
                if (obj.has("house_number"))
                    loc.setStreetNumber(obj.getString("house_number"));
                if (obj.has("road"))
                    loc.setRoute(obj.getString("road"));
                if (obj.has("city"))
                    loc.setLocality(obj.getString("city"));
                if (obj.has("county"))
                    loc.setAdministrativeAreaLevel2(obj.getString("county"));
                if (obj.has("state"))
                    loc.setAdministrativeAreaLevel1(obj.getString("state"));
                if (obj.has("postcode"))
                    loc.setPostalCode(obj.getString("postcode"));
                if (obj.has("country_code"))
                    loc.setCountry(obj.getString("country_code").toUpperCase());
            }
            locations.add(loc);
        }
    } catch (JSONException e) {
        throw new GeocodingException(e.getMessage(), e);
    }
    return locations;
}