List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static JSONObject addtemp(JSONObject temp, String id, Object text) throws JSONException { if (!temp.has(id)) { temp.put(id, text);//from w ww. j av a 2 s . c om } return temp; }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
private static void addRepeatToJson(JSONObject out, Element root, Repeat f, String permlevel, JSONObject tempSon, String csid, String ims_url) throws JSONException { if (f.getXxxServicesNoRepeat()) { //not a repeat in services yet but is a repeat in UI FieldSet[] fields = f.getChildren(permlevel); if (fields.length == 0) return; JSONArray members = new JSONArray(); JSONObject data = new JSONObject(); addFieldSetToJson(data, root, fields[0], permlevel, tempSon, csid, ims_url); members.put(data);//from w ww . ja v a2s .c om out.put(f.getID(), members); return; } String nodeName = f.getServicesTag(); if (f.hasServicesParent()) { nodeName = f.getfullID(); //XXX hack because of weird repeats in accountroles permroles etc if (f.getServicesParent().length == 0) { nodeName = f.getID(); } } List<?> nodes = root.selectNodes(nodeName); if (nodes.size() == 0) {// add in empty primary tags and arrays etc to help UI if (f.asSibling()) { JSONObject repeated = new JSONObject(); if (f.hasPrimary()) { repeated.put("_primary", true); } if (!out.has(f.getID())) { JSONArray temp = new JSONArray(); out.put(f.getID(), temp); } out.getJSONArray(f.getID()).put(repeated); } else { JSONArray repeatitem = new JSONArray(); out.put(f.getID(), repeatitem); } return; } // Only first element is important in container //except when we have repeating items int pos = 0; for (Object repeatcontainer : nodes) { pos++; Element container = (Element) repeatcontainer; if (f.asSibling()) { JSONArray repeatitem = addRepeatedNodeToJson(container, f, permlevel, tempSon); JSONArray temp = new JSONArray(); if (!out.has(f.getID())) { out.put(f.getID(), temp); } for (int arraysize = 0; arraysize < repeatitem.length(); arraysize++) { JSONObject repeated = repeatitem.getJSONObject(arraysize); if (f.hasPrimary() && pos == 1) { repeated.put("_primary", true); } out.getJSONArray(f.getID()).put(repeated); } } else { JSONArray repeatitem = addRepeatedNodeToJson(container, f, permlevel, tempSon); out.put(f.getID(), repeatitem); } } }
From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java
public static JSONObject convertToJson(JSONObject out, Record r, Document doc, String operation, String section, String csid, String ims_url) throws JSONException { Element root = doc.getRootElement(); JSONObject tempSon = new JSONObject(); for (FieldSet f : r.getAllServiceFieldTopLevel(operation, section)) { addFieldSetToJson(out, root, f, operation, tempSon, csid, ims_url); }/*from w w w . j av a 2s . c o m*/ if (r.hasMerged()) { for (FieldSet f : r.getAllMergedFields()) { for (String fm : f.getAllMerge()) { if (fm != null) { if (r.hasFieldByOperation(fm, operation)) { if (tempSon.has(fm)) { String data = tempSon.getString(fm); if (data != null && !data.equals("") && !out.has(f.getID())) { out.put(f.getID(), data); } } } } } } } return tempSon; }
From source file:com.rsimiao.exemplosloopj.UsuarioWS.java
public void buscar(final Handler handler) { try {/* w w w . j av a 2s. c o m*/ RequestParams parametros = new RequestParams(); parametros.add("limite", "todos"); Wscliente.post(url, parametros, new AsyncHttpResponseHandler() { @Override public void onFailure(int code, Header[] header, byte[] conteudo, Throwable arg3) { //voc pode colocar aqui seu tratamento de erro Log.d("WS USUARIO", "DEU ERRO"); Message msg = new Message(); msg.what = 0; //defino um identificador para a msg coloco 1 para sucesso e 0 para erro. handler.sendMessage(msg); } @Override public void onSuccess(int code, Header[] header, byte[] conteudo) { try { JSONObject json = new JSONObject(new String(conteudo)); List<Usuario> usuarios = new ArrayList<Usuario>(); //sua lgica para tratar o json recebido (no precisa ser desse modo jurstico) if (json.has("status") && json.getString("status").equalsIgnoreCase("success")) { JSONArray jUsrs = json.getJSONArray("usuarios"); for (int i = 0; i < jUsrs.length(); i++) { Usuario u = new Usuario(); u.setNome(jUsrs.getJSONObject(i).getString("nome")); u.setUsuario(jUsrs.getJSONObject(i).getString("usuario")); u.setLogged(jUsrs.getJSONObject(i).getBoolean("islogged")); usuarios.add(u); } Message msg = new Message(); msg.what = 1; //defino um identificador para a msg coloco 1 para sucesso e 0 para erro. msg.obj = usuarios; handler.sendMessage(msg); } } catch (JSONException e) { e.printStackTrace(); } } }); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.markupartist.sthlmtraveling.provider.planner.JourneyQuery.java
public static JourneyQuery fromJson(JSONObject jsonObject) throws JSONException { JourneyQuery journeyQuery = new JourneyQuery.Builder().origin(jsonObject.getJSONObject("origin")) .destination(jsonObject.getJSONObject("destination")) .transportModes(jsonObject.has("transportModes") ? jsonObject.getJSONArray("transportModes") : null) .create();// ww w . j a va 2s .com if (jsonObject.has("isTimeDeparture")) { journeyQuery.isTimeDeparture = jsonObject.getBoolean("isTimeDeparture"); } if (jsonObject.has("alternativeStops")) { journeyQuery.alternativeStops = jsonObject.getBoolean("alternativeStops"); } if (jsonObject.has("via")) { JSONObject jsonVia = jsonObject.getJSONObject("via"); Location via = new Location(); via.name = jsonVia.getString("name"); journeyQuery.via = via; } return journeyQuery; }
From source file:org.everit.json.schema.IssueTest.java
private void readExpectedValues(final JSONObject expected) { expectedFailureList.add((String) expected.get("message")); if (expected.has("causingExceptions")) { JSONArray causingEx = expected.getJSONArray("causingExceptions"); for (Object subJson : causingEx) { readExpectedValues((JSONObject) subJson); }//from ww w. j a v a 2 s.c om } }
From source file:com.android.i18n.addressinput.FormatInterpreter.java
private static String getJsonValue(String regionCode, AddressDataKey key) { Util.checkNotNull(regionCode); String jsonString = RegionDataConstants.getCountryFormatMap().get(regionCode); Util.checkNotNull(jsonString, "no json data for region code " + regionCode); try {//from w w w . jav a 2 s . c o m JSONObject jsonObj = new JSONObject(new JSONTokener(jsonString)); if (!jsonObj.has(key.name().toLowerCase())) { // Key not found. Return null. return null; } // Gets the string for this key. String parsedJsonString = jsonObj.getString(key.name().toLowerCase()); return parsedJsonString; } catch (JSONException e) { throw new RuntimeException("Invalid json for region code " + regionCode + ": " + jsonString); } }
From source file:edu.umass.cs.gigapaxos.paxospackets.FindReplicaGroupPacket.java
public FindReplicaGroupPacket(JSONObject msg) throws JSONException { super(msg);/* ww w .jav a2 s .c o m*/ this.packetType = PaxosPacketType.FIND_REPLICA_GROUP; this.nodeID = msg.getInt(PaxosPacket.NodeIDKeys.SNDR.toString()); JSONArray jsonGroup = null; if (msg.has(PaxosPacket.NodeIDKeys.GROUP.toString())) { jsonGroup = msg.getJSONArray(PaxosPacket.NodeIDKeys.GROUP.toString()); } if (jsonGroup != null && jsonGroup.length() > 0) { this.group = new int[jsonGroup.length()]; for (int i = 0; i < jsonGroup.length(); i++) { this.group[i] = Integer.valueOf(jsonGroup.getString(i)); } } else this.group = null; }
From source file:edu.umass.cs.gigapaxos.paxospackets.FindReplicaGroupPacket.java
public static int getNodeID(JSONObject msg) throws JSONException { int id = -1;//from ww w.j a v a2s .c om if (msg.has(PaxosPacket.Keys.PT.toString())) { PaxosPacketType msgType = PaxosPacketType .getPaxosPacketType(msg.getInt(PaxosPacket.Keys.PT.toString())); switch (msgType) { case ACCEPT: id = msg.getInt(PaxosPacket.NodeIDKeys.SNDR.toString()); break; case ACCEPT_REPLY: id = msg.getInt(PaxosPacket.NodeIDKeys.SNDR.toString()); break; case PREPARE: id = (new Ballot(msg.getString(PaxosPacket.NodeIDKeys.B.toString()))).coordinatorID; // msg.getInt(PaxosPacket.NodeIDKeys.COORDINATOR.toString()); break; case DECISION: id = (new Ballot(msg.getString(PaxosPacket.NodeIDKeys.B.toString()))).coordinatorID; break; default: break; } } return id; }
From source file:edu.stanford.mobisocial.dungbeetle.MessagingManagerThread.java
private void handleIncomingMessage(final IncomingMessage incoming) { final SignedObj contents = incoming.contents(); final long hash = contents.getHash(); if (contents.getSender() == null) { Log.e(TAG, "Null sender for " + contents.getType() + ", " + contents.getJson()); return;/*from w w w . j a v a 2 s . c o m*/ } final String personId = contents.getSender().getId(); // final String personId = incoming.from(); /** * TODO: This needs to be updated with the POSI standards to accept a * SignedObj. */ if (DBG) Log.i(TAG, "Localized contents: " + contents); try { JSONObject in_obj = contents.getJson(); String feedName = contents.getFeedName(); String type = contents.getType(); Uri feedPreUri = Feed.uriForName(feedName); if (mMessageDropHandler.preFiltersObj(mContext, feedPreUri)) { return; } if (mHelper.queryAlreadyReceived(hash)) { if (DBG) Log.i(TAG, "Message already received: " + hash); return; } Maybe<Contact> contact = mHelper.contactForPersonId(personId); final DbEntryHandler objHandler = DbObjects.getObjHandler(in_obj); byte[] extracted_data = null; if (objHandler instanceof UnprocessedMessageHandler) { Pair<JSONObject, byte[]> r = ((UnprocessedMessageHandler) objHandler).handleUnprocessed(mContext, in_obj); if (r != null) { in_obj = r.first; extracted_data = r.second; } } final JSONObject obj = in_obj; final byte[] raw = extracted_data; /** * TODO STFAN BJDODSON KANAKB * * See FriendAcceptObj.handleUnprocessed as template, code is something like: * * if (!mPublicKeyDirectory.verify(in_obj.getString("email"), in_obj.getPublicKey())) { * Log.w("Spammer trying to claim public key for email address"); * return; * } * if (inAddressBook(email)) { * // auto-accept and notify of new friend * } else { * // notification to accept friend * } */ if (!contact.isKnown()) { Log.i(TAG, "Message from unknown contact. " + contents); return; } /** * Run handlers over all received objects: */ long objId; final Contact realContact = contact.get(); long contactId = realContact.id; if (DBG) Log.d(TAG, "Msg from " + contactId + " ( " + realContact.name + ")"); // Insert into the database. (TODO: Handler, both android.os and // musubi.core) if (!objHandler.handleObjFromNetwork(mContext, realContact, obj)) { return; } Integer intKey = null; if (obj.has(DbObjects.JSON_INT_KEY)) { intKey = obj.getInt(DbObjects.JSON_INT_KEY); obj.remove(DbObjects.JSON_INT_KEY); } objId = mHelper.addObjectByJson(contact.otherwise(Contact.NA()).id, obj, hash, raw, intKey); Uri feedUri; if (feedName.equals("friend")) { feedUri = Feed.uriForName("friend/" + contactId); } else { feedUri = Feed.uriForName(feedName); } mContext.getContentResolver().notifyChange(feedUri, null); if (feedName.equals("direct") || feedName.equals("friend")) { long time = obj.optLong(DbObject.TIMESTAMP); Helpers.updateLastPresence(mContext, realContact, time); objHandler.handleDirectMessage(mContext, realContact, obj); } /** * Run handlers over all received objects: */ // TODO: framework code. DbObj signedObj = App.instance().getMusubi().objForId(objId); getFromNetworkHandlers().handleObj(mContext, DbObjects.forType(type), signedObj); objHandler.afterDbInsertion(mContext, signedObj); } catch (Exception e) { Log.e(TAG, "Error handling incoming message.", e); } }