use of org.json.JSONTokener in project SmartAndroidSource by jaychou2012.
the class JsonHttpResponseHandler method parseResponse.
/**
* Returns Object of type {@link JSONObject}, {@link JSONArray}, String, Boolean, Integer, Long,
* Double or {@link JSONObject#NULL}, see {@link org.json.JSONTokener#nextValue()}
*
* @param responseBody response bytes to be assembled in String and parsed as JSON
* @return Object parsedResponse
* @throws org.json.JSONException exception if thrown while parsing JSON
*/
protected Object parseResponse(byte[] responseBody) throws JSONException {
if (null == responseBody)
return null;
Object result = null;
//trim the string to prevent start with blank, and test if the string is valid JSON, because the parser don't do this :(. If JSON is not valid this will return null
String jsonString = getResponseString(responseBody, getCharset());
if (jsonString != null) {
jsonString = jsonString.trim();
if (jsonString.startsWith("{") || jsonString.startsWith("[")) {
result = new JSONTokener(jsonString).nextValue();
}
}
if (result == null) {
result = jsonString;
}
return result;
}
use of org.json.JSONTokener in project phonegap-facebook-plugin by Wizcorp.
the class Utility method getStringPropertyAsJSON.
// Returns either a JSONObject or JSONArray representation of the 'key' property of 'jsonObject'.
public static Object getStringPropertyAsJSON(JSONObject jsonObject, String key, String nonJSONPropertyKey) throws JSONException {
Object value = jsonObject.opt(key);
if (value != null && value instanceof String) {
JSONTokener tokener = new JSONTokener((String) value);
value = tokener.nextValue();
}
if (value != null && !(value instanceof JSONObject || value instanceof JSONArray)) {
if (nonJSONPropertyKey != null) {
// Facebook sometimes gives us back a non-JSON value such as
// literal "true" or "false" as a result.
// If we got something like that, we present it to the caller as
// a GraphObject with a single
// property. We only do this if the caller wants that behavior.
jsonObject = new JSONObject();
jsonObject.putOpt(nonJSONPropertyKey, value);
return jsonObject;
} else {
throw new FacebookException("Got an unexpected non-JSON object.");
}
}
return value;
}
use of org.json.JSONTokener in project qi4j-sdk by Qi4j.
the class MapEntityStoreMixin method readEntityState.
protected EntityState readEntityState(DefaultEntityStoreUnitOfWork unitOfWork, Reader entityState) throws EntityStoreException {
try {
Module module = unitOfWork.module();
JSONObject jsonObject = new JSONObject(new JSONTokener(entityState));
EntityStatus status = EntityStatus.LOADED;
String version = jsonObject.getString(JSONKeys.VERSION);
long modified = jsonObject.getLong(JSONKeys.MODIFIED);
String identity = jsonObject.getString(JSONKeys.IDENTITY);
// Check if version is correct
String currentAppVersion = jsonObject.optString(JSONKeys.APPLICATION_VERSION, "0.0");
if (!currentAppVersion.equals(application.version())) {
if (migration != null) {
migration.migrate(jsonObject, application.version(), this);
} else {
// Do nothing - set version to be correct
jsonObject.put(JSONKeys.APPLICATION_VERSION, application.version());
}
LoggerFactory.getLogger(MapEntityStoreMixin.class).debug("Updated version nr on " + identity + " from " + currentAppVersion + " to " + application.version());
// State changed
status = EntityStatus.UPDATED;
}
String type = jsonObject.getString(JSONKeys.TYPE);
EntityDescriptor entityDescriptor = module.entityDescriptor(type);
if (entityDescriptor == null) {
throw new EntityTypeNotFoundException(type);
}
Map<QualifiedName, Object> properties = new HashMap<>();
JSONObject props = jsonObject.getJSONObject(JSONKeys.PROPERTIES);
for (PropertyDescriptor propertyDescriptor : entityDescriptor.state().properties()) {
Object jsonValue;
try {
jsonValue = props.get(propertyDescriptor.qualifiedName().name());
} catch (JSONException e) {
// Value not found, default it
Object initialValue = propertyDescriptor.initialValue(module);
properties.put(propertyDescriptor.qualifiedName(), initialValue);
status = EntityStatus.UPDATED;
continue;
}
if (JSONObject.NULL.equals(jsonValue)) {
properties.put(propertyDescriptor.qualifiedName(), null);
} else {
Object value = valueSerialization.deserialize(propertyDescriptor.valueType(), jsonValue.toString());
properties.put(propertyDescriptor.qualifiedName(), value);
}
}
Map<QualifiedName, EntityReference> associations = new HashMap<>();
JSONObject assocs = jsonObject.getJSONObject(JSONKeys.ASSOCIATIONS);
for (AssociationDescriptor associationType : entityDescriptor.state().associations()) {
try {
Object jsonValue = assocs.get(associationType.qualifiedName().name());
EntityReference value = jsonValue == JSONObject.NULL ? null : EntityReference.parseEntityReference((String) jsonValue);
associations.put(associationType.qualifiedName(), value);
} catch (JSONException e) {
// Association not found, default it to null
associations.put(associationType.qualifiedName(), null);
status = EntityStatus.UPDATED;
}
}
JSONObject manyAssocs = jsonObject.getJSONObject(JSONKeys.MANY_ASSOCIATIONS);
Map<QualifiedName, List<EntityReference>> manyAssociations = new HashMap<>();
for (AssociationDescriptor manyAssociationType : entityDescriptor.state().manyAssociations()) {
List<EntityReference> references = new ArrayList<>();
try {
JSONArray jsonValues = manyAssocs.getJSONArray(manyAssociationType.qualifiedName().name());
for (int i = 0; i < jsonValues.length(); i++) {
Object jsonValue = jsonValues.getString(i);
EntityReference value = jsonValue == JSONObject.NULL ? null : EntityReference.parseEntityReference((String) jsonValue);
references.add(value);
}
manyAssociations.put(manyAssociationType.qualifiedName(), references);
} catch (JSONException e) {
// ManyAssociation not found, default to empty one
manyAssociations.put(manyAssociationType.qualifiedName(), references);
}
}
JSONObject namedAssocs = jsonObject.getJSONObject(JSONKeys.NAMED_ASSOCIATIONS);
Map<QualifiedName, Map<String, EntityReference>> namedAssociations = new HashMap<>();
for (AssociationDescriptor namedAssociationType : entityDescriptor.state().namedAssociations()) {
Map<String, EntityReference> references = new LinkedHashMap<>();
try {
JSONObject jsonValues = namedAssocs.getJSONObject(namedAssociationType.qualifiedName().name());
JSONArray names = jsonValues.names();
if (names != null) {
for (int idx = 0; idx < names.length(); idx++) {
String name = names.getString(idx);
Object value = jsonValues.get(name);
EntityReference ref = value == JSONObject.NULL ? null : EntityReference.parseEntityReference((String) value);
references.put(name, ref);
}
}
namedAssociations.put(namedAssociationType.qualifiedName(), references);
} catch (JSONException e) {
// NamedAssociation not found, default to empty one
namedAssociations.put(namedAssociationType.qualifiedName(), references);
}
}
return new DefaultEntityState(unitOfWork, version, modified, EntityReference.parseEntityReference(identity), status, entityDescriptor, properties, associations, manyAssociations, namedAssociations);
} catch (JSONException e) {
throw new EntityStoreException(e);
}
}
use of org.json.JSONTokener in project YourEyes by SevenLJY.
the class JsonParser method parseGrammarResult.
public static String parseGrammarResult(String json) {
StringBuffer ret = new StringBuffer();
try {
JSONTokener tokener = new JSONTokener(json);
JSONObject joResult = new JSONObject(tokener);
JSONArray words = joResult.getJSONArray("ws");
for (int i = 0; i < words.length(); i++) {
JSONArray items = words.getJSONObject(i).getJSONArray("cw");
for (int j = 0; j < items.length(); j++) {
JSONObject obj = items.getJSONObject(j);
if (obj.getString("w").contains("nomatch")) {
ret.append("没有匹配结果.");
return ret.toString();
}
ret.append("【结果】" + obj.getString("w"));
ret.append("【置信度】" + obj.getInt("sc"));
ret.append("\n");
}
}
} catch (Exception e) {
e.printStackTrace();
ret.append("没有匹配结果.");
}
return ret.toString();
}
use of org.json.JSONTokener in project zxing by zxing.
the class BookResultInfoRetriever method retrieveSupplementalInfo.
@Override
void retrieveSupplementalInfo() throws IOException {
CharSequence contents = HttpHelper.downloadViaHttp("https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);
if (contents.length() == 0) {
return;
}
String title;
String pages;
Collection<String> authors = null;
try {
JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
JSONArray items = topLevel.optJSONArray("items");
if (items == null || items.isNull(0)) {
return;
}
JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
if (volumeInfo == null) {
return;
}
title = volumeInfo.optString("title");
pages = volumeInfo.optString("pageCount");
JSONArray authorsArray = volumeInfo.optJSONArray("authors");
if (authorsArray != null && !authorsArray.isNull(0)) {
authors = new ArrayList<>(authorsArray.length());
for (int i = 0; i < authorsArray.length(); i++) {
authors.add(authorsArray.getString(i));
}
}
} catch (JSONException e) {
throw new IOException(e);
}
Collection<String> newTexts = new ArrayList<>();
maybeAddText(title, newTexts);
maybeAddTextSeries(authors, newTexts);
maybeAddText(pages == null || pages.isEmpty() ? null : pages + "pp.", newTexts);
String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context) + "/search?tbm=bks&source=zxing&q=";
append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}
Aggregations