List of usage examples for org.json JSONException JSONException
public JSONException(Throwable t)
From source file:com.norman0406.slimgress.API.Item.ItemBase.java
protected ItemBase(ItemType type, JSONArray json) throws JSONException { super(json);// ww w . j a va 2s . c o m mItemType = type; JSONObject item = json.getJSONObject(2); JSONObject itemResource = null; if (item.has("resource")) itemResource = item.getJSONObject("resource"); else if (item.has("resourceWithLevels")) itemResource = item.getJSONObject("resourceWithLevels"); else if (item.has("modResource")) itemResource = item.getJSONObject("modResource"); else throw new JSONException("resource not found"); if (itemResource.has("resourceRarity") || itemResource.has("rarity")) { String rarity = null; if (itemResource.has("resourceRarity")) rarity = itemResource.getString("resourceRarity"); else if (itemResource.has("rarity")) rarity = itemResource.getString("rarity"); else throw new RuntimeException("unknown rarity string"); if (mItemRarity != null) { if (rarity.equals("VERY_COMMON")) mItemRarity = ItemBase.Rarity.VeryCommon; else if (rarity.equals("COMMON")) mItemRarity = ItemBase.Rarity.Common; else if (rarity.equals("LESS_COMMON")) mItemRarity = ItemBase.Rarity.LessCommon; else if (rarity.equals("RARE")) mItemRarity = ItemBase.Rarity.Rare; else if (rarity.equals("VERY_RARE")) mItemRarity = ItemBase.Rarity.VeryRare; else if (rarity.equals("EXTREMELY_RARE")) mItemRarity = ItemBase.Rarity.ExtraRare; } } if (itemResource.has("level")) { int level = itemResource.getInt("level"); mItemAccessLevel = level; } JSONObject itemInInventory = item.getJSONObject("inInventory"); mItemPlayerId = itemInInventory.getString("playerId"); mItemAcquisitionTimestamp = itemInInventory.getString("acquisitionTimestampMs"); }
From source file:org.official.json.HTTP.java
/** * Convert a JSONObject into an HTTP header. A request header must contain * <pre>{//www. j a v a2 s . c o m * Method: "POST" (for example), * "Request-URI": "/" (for example), * "HTTP-Version": "HTTP/1.1" (for example) * }</pre> * A response header must contain * <pre>{ * "HTTP-Version": "HTTP/1.1" (for example), * "Status-Code": "200" (for example), * "Reason-Phrase": "OK" (for example) * }</pre> * Any other members of the JSONObject will be output as HTTP fields. * The result will end with two CRLF pairs. * @param jo A JSONObject * @return An HTTP header string. * @throws JSONException if the object does not contain enough * information. */ public static String toString(JSONObject jo) throws JSONException { Iterator<String> keys = jo.keys(); String string; StringBuilder sb = new StringBuilder(); if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { sb.append(jo.getString("HTTP-Version")); sb.append(' '); sb.append(jo.getString("Status-Code")); sb.append(' '); sb.append(jo.getString("Reason-Phrase")); } else if (jo.has("Method") && jo.has("Request-URI")) { sb.append(jo.getString("Method")); sb.append(' '); sb.append('"'); sb.append(jo.getString("Request-URI")); sb.append('"'); sb.append(' '); sb.append(jo.getString("HTTP-Version")); } else { throw new JSONException("Not enough material for an HTTP header."); } sb.append(CRLF); while (keys.hasNext()) { string = keys.next(); if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) { sb.append(string); sb.append(": "); sb.append(jo.getString(string)); sb.append(CRLF); } } sb.append(CRLF); return sb.toString(); }
From source file:com.vk.sdkweb.api.model.ParseUtils.java
/** * Parses object with follow rules:/*from w w w . jav a2 s . co m*/ * * 1. All fields should had a public access. * 2. The name of the filed should be fully equal to name of JSONObject key. * 3. Supports parse of all Java primitives, all {@link java.lang.String}, * arrays of primitive types, {@link java.lang.String}s and {@link com.vk.sdkweb.api.model.VKApiModel}s, * list implementation line {@link com.vk.sdkweb.api.model.VKList}, {@link com.vk.sdkweb.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdkweb.api.model.VKPhotoSizes}, * {@link com.vk.sdkweb.api.model.VKApiModel}s. * * 4. Boolean fields defines by vk_int == 1 expression. * * @param object object to initialize * @param source data to read values * @param <T> type of result * @return initialized according with given data object * @throws JSONException if source object structure is invalid */ @SuppressWarnings("rawtypes") public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException { if (source.has("response")) { source = source.optJSONObject("response"); } if (source == null) { return object; } for (Field field : object.getClass().getFields()) { field.setAccessible(true); String fieldName = field.getName(); Class<?> fieldType = field.getType(); Object value = source.opt(fieldName); if (value == null) { continue; } try { if (fieldType.isPrimitive() && value instanceof Number) { Number number = (Number) value; if (fieldType.equals(int.class)) { field.setInt(object, number.intValue()); } else if (fieldType.equals(long.class)) { field.setLong(object, number.longValue()); } else if (fieldType.equals(float.class)) { field.setFloat(object, number.floatValue()); } else if (fieldType.equals(double.class)) { field.setDouble(object, number.doubleValue()); } else if (fieldType.equals(boolean.class)) { field.setBoolean(object, number.intValue() == 1); } else if (fieldType.equals(short.class)) { field.setShort(object, number.shortValue()); } else if (fieldType.equals(byte.class)) { field.setByte(object, number.byteValue()); } } else { Object result = field.get(object); if (value.getClass().equals(fieldType)) { result = value; } else if (fieldType.isArray() && value instanceof JSONArray) { result = parseArrayViaReflection((JSONArray) value, fieldType); } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) { Constructor<?> constructor = fieldType.getConstructor(JSONArray.class); result = constructor.newInstance((JSONArray) value); } else if (VKList.class.equals(fieldType)) { ParameterizedType genericTypes = (ParameterizedType) field.getGenericType(); Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0]; if (VKApiModel.class.isAssignableFrom(genericType) && Parcelable.class.isAssignableFrom(genericType) && Identifiable.class.isAssignableFrom(genericType)) { if (value instanceof JSONArray) { result = new VKList((JSONArray) value, genericType); } else if (value instanceof JSONObject) { result = new VKList((JSONObject) value, genericType); } } } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) { result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value); } field.set(object, result); } } catch (InstantiationException e) { throw new JSONException(e.getMessage()); } catch (IllegalAccessException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodException e) { throw new JSONException(e.getMessage()); } catch (InvocationTargetException e) { throw new JSONException(e.getMessage()); } catch (NoSuchMethodError e) { // ?: // , getFields() . // ? ? ?, ? ?, Android ? . throw new JSONException(e.getMessage()); } } return object; }
From source file:com.vk.sdkweb.api.model.ParseUtils.java
/** * Parses array from given JSONArray./*w ww. jav a2 s. com*/ * Supports parsing of primitive types and {@link com.vk.sdkweb.api.model.VKApiModel} instances. * @param array JSONArray to parse * @param arrayClass type of array field in class. * @return object to set to array field in class * @throws JSONException if given array have incompatible type with given field. */ private static Object parseArrayViaReflection(JSONArray array, Class arrayClass) throws JSONException { Object result = Array.newInstance(arrayClass.getComponentType(), array.length()); Class<?> subType = arrayClass.getComponentType(); for (int i = 0; i < array.length(); i++) { try { Object item = array.opt(i); if (VKApiModel.class.isAssignableFrom(subType) && item instanceof JSONObject) { VKApiModel model = (VKApiModel) subType.newInstance(); item = model.parse((JSONObject) item); } Array.set(result, i, item); } catch (InstantiationException e) { throw new JSONException(e.getMessage()); } catch (IllegalAccessException e) { throw new JSONException(e.getMessage()); } catch (IllegalArgumentException e) { throw new JSONException(e.getMessage()); } } return result; }
From source file:com.gmx.library.JsonUtils.java
public static JSONArray object2Json(Object data) throws JSONException { if (!data.getClass().isArray()) { throw new JSONException("Not a primitive data: " + data.getClass()); }/*from w ww. j a va2s.c o m*/ final int length = Array.getLength(data); JSONArray jsonArray = new JSONArray(); for (int i = 0; i < length; ++i) { jsonArray.put(wrap(Array.get(data, i))); } return jsonArray; }
From source file:com.facebook.config.ClassExtractor.java
@Override public Class<?> extract(String key, JSONObject jsonObject) throws JSONException { try {//from www. j a va 2 s . c o m return Class.forName(jsonObject.getString(key)); } catch (ClassNotFoundException e) { throw new JSONException(e); } }
From source file:com.yunmall.ymsdk.net.http.JsonHttpResponseHandler.java
@Override public final void onSuccess(final int statusCode, final Header[] headers, final byte[] responseBytes) { if (statusCode != HttpStatus.SC_NO_CONTENT) { Runnable parser = new Runnable() { @Override//from ww w . j a v a 2 s . co m public void run() { try { final Object jsonResponse = parseResponse(responseBytes); postRunnable(new Runnable() { @Override public void run() { if (jsonResponse == null) { onFailure(statusCode, headers, new JSONException("jsonResponse is null"), (JSONObject) null); } else if (jsonResponse instanceof JSONObject) { onSuccess(statusCode, headers, (JSONObject) jsonResponse); } else if (jsonResponse instanceof JSONArray) { onSuccess(statusCode, headers, (JSONArray) jsonResponse); } else if (jsonResponse instanceof String) { onFailure(statusCode, headers, (String) jsonResponse, new JSONException("Response cannot be parsed as JSON data")); } else { onFailure(statusCode, headers, new JSONException( "Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null); } } }); } catch (final JSONException ex) { postRunnable(new Runnable() { @Override public void run() { onFailure(statusCode, headers, ex, (JSONObject) null); } }); } } }; if (!getUseSynchronousMode()) { // new Thread(parser).start(); CacheThreadPool.getInstance().submit(parser); } else { // In synchronous mode everything should be run on one thread parser.run(); } } else { onSuccess(statusCode, headers, new JSONObject()); } }
From source file:com.yunmall.ymsdk.net.http.JsonHttpResponseHandler.java
@Override public final void onFailure(final int statusCode, final Header[] headers, final byte[] responseBytes, final Throwable throwable) { if (responseBytes != null) { Runnable parser = new Runnable() { @Override// ww w . j av a2s .co m public void run() { try { final Object jsonResponse = parseResponse(responseBytes); postRunnable(new Runnable() { @Override public void run() { if (jsonResponse instanceof JSONObject) { onFailure(statusCode, headers, throwable, (JSONObject) jsonResponse); } else if (jsonResponse instanceof JSONArray) { onFailure(statusCode, headers, throwable, (JSONArray) jsonResponse); } else if (jsonResponse instanceof String) { onFailure(statusCode, headers, (String) jsonResponse, throwable); } else { onFailure(statusCode, headers, new JSONException( "Unexpected response type " + jsonResponse.getClass().getName()), (JSONObject) null); } } }); } catch (final JSONException ex) { postRunnable(new Runnable() { @Override public void run() { onFailure(statusCode, headers, ex, (JSONObject) null); } }); } } }; if (!getUseSynchronousMode()) { // new Thread(parser).start(); CacheThreadPool.getInstance().submit(parser); } else { // In synchronous mode everything should be run on one thread parser.run(); } } else { YmLog.v(LOG_TAG, "response body is null, calling onFailure(Throwable, JSONObject)"); onFailure(statusCode, headers, throwable, (JSONObject) null); } }
From source file:com.github.e2point718.har2jmx.HAR.java
public static HAR build(String source) { HAR h = new HAR(); JSONObject har = new JSONObject(source); JSONObject log = har.getJSONObject("log"); JSONArray jPages = getOptionalArray(log, "pages"); Map<String, Page> pages = new HashMap<>(); if (jPages != null) { h.pages = new Page[jPages.length()]; for (int i = 0; i < jPages.length(); i++) { JSONObject jPage = jPages.getJSONObject(i); Page page = new Page(); h.pages[i] = page;//from www.j ava 2 s .com page.id = jPage.getString("id"); page.title = jPage.getString("title"); pages.put(page.id, page); } } JSONArray jEntries = getOptionalArray(log, "entries"); if (jEntries != null) { h.entries = new Entry[jEntries.length()]; for (int i = 0; i < jEntries.length(); i++) { JSONObject jEntry = jEntries.getJSONObject(i); Entry entry = new Entry(); h.entries[i] = entry; entry.pageref = pages.get(getOptionalProperty(jEntry, "pageref")); JSONObject jRequest = jEntry.getJSONObject("request"); Request request = new Request(); entry.request = request; request.httpVersion = jRequest.getString("httpVersion"); request.method = Method.valueOf(jRequest.getString("method")); try { request.url = new URL(jRequest.getString("url")); } catch (MalformedURLException e) { throw new JSONException(e.getMessage()); } JSONArray jHeaders = getOptionalArray(jRequest, "headers"); if (jHeaders != null) { request.headers = new HashMap<>(); for (int j = 0; j < jHeaders.length(); j++) { JSONObject jHeader = jHeaders.getJSONObject(j); request.headers.put(jHeader.getString("name"), jHeader.getString("value")); } } JSONArray jQueryString = getOptionalArray(jRequest, "queryString"); if (jQueryString != null) { request.queryString = new HashMap<>(); for (int j = 0; j < jQueryString.length(); j++) { JSONObject jQueryStringO = jQueryString.getJSONObject(j); request.queryString.put(jQueryStringO.getString("name"), jQueryStringO.getString("value")); } } JSONArray jCookies = getOptionalArray(jRequest, "cookies"); if (jCookies != null) { request.cookies = new Cookie[jCookies.length()]; for (int j = 0; j < jCookies.length(); j++) { JSONObject jCookie = jCookies.getJSONObject(j); Cookie cookie = new Cookie(); request.cookies[j] = cookie; cookie.name = jCookie.getString("name"); cookie.value = jCookie.getString("value"); } } JSONObject jPostData = getOptionalObject(jRequest, ("postData")); if (jPostData != null) { PostData pd = new PostData(); request.postData = pd; pd.mimeType = jPostData.getString("mimeType"); pd.text = getOptionalProperty(jPostData, "text"); JSONArray jPostParams = getOptionalArray(jPostData, "params"); if (jPostParams != null) { pd.params = new PostDataParam[jPostParams.length()]; for (int j = 0; j < jPostParams.length(); j++) { PostDataParam pdp = new PostDataParam(); JSONObject jPostDataParam = jPostParams.getJSONObject(j); pd.params[j] = pdp; pdp.name = getOptionalProperty(jPostDataParam, "name"); pdp.value = getOptionalProperty(jPostDataParam, "value"); pdp.contentType = getOptionalProperty(jPostDataParam, "contentType"); pdp.fileName = getOptionalProperty(jPostDataParam, "fileName"); } } } JSONObject jResponse = jEntry.getJSONObject("response"); Response response = new Response(); entry.response = response; response.httpVersion = jResponse.getString("httpVersion"); response.status = jResponse.getInt("status"); response.statusText = jResponse.getString("statusText"); jHeaders = getOptionalArray(jResponse, "headers"); if (jHeaders != null) { response.headers = new HashMap<>(); for (int j = 0; j < jHeaders.length(); j++) { JSONObject jHeader = jHeaders.getJSONObject(j); response.headers.put(jHeader.getString("name"), jHeader.getString("value")); } } jCookies = getOptionalArray(jResponse, "cookies"); if (jCookies != null) { response.cookies = new Cookie[jCookies.length()]; for (int j = 0; j < jCookies.length(); j++) { JSONObject jCookie = jCookies.getJSONObject(j); Cookie cookie = new Cookie(); response.cookies[j] = cookie; cookie.name = jCookie.getString("name"); cookie.value = jCookie.getString("value"); } } JSONObject jContent = getOptionalObject(jResponse, ("content")); if (jContent != null) { ResponseContent content = new ResponseContent(); response.content = content; content.size = jContent.getLong("size"); content.mimeType = jContent.getString("mimeType"); content.text = getOptionalProperty(jContent, ("text")); } } } return h; }
From source file:es.upm.dit.xsdinferencer.XSDInferencer.java
/** * Method that, given an args array, does the whole inference process by calling the appropriate submodules. * @param args the args array, as provided by {@link XSDInferencer#main(String[])} * @return a {@link Results} object with the inference results (both statistics and XSDs) * @throws XSDConfigurationException if there is a problem with the configuration * @throws IOException if there is an I/O problem while reading the input XML files or writing the output files * @throws JDOMException if there is any problem while parsing the input XML files *//* w ww .j a va 2 s . c o m*/ public Results inferSchema(String[] args) throws XSDInferencerException { try { XSDInferenceConfiguration configuration = new XSDInferenceConfiguration(args); FilenameFilter filenameFilter; if (configuration.getWorkingFormat().equals("xml")) { filenameFilter = FILE_NAME_FILTER_XML_EXTENSION; List<File> xmlFiles = getInstanceFileNames(args, filenameFilter); List<Document> xmlDocuments = new ArrayList<>(xmlFiles.size()); SAXBuilder saxBuilder = new SAXBuilder(); for (int i = 0; i < xmlFiles.size(); i++) { File xmlFile = xmlFiles.get(i); System.out.print("Reading input file " + xmlFile.getName() + "..."); FileInputStream fis = new FileInputStream(xmlFile); //BufferedReader reader = new BufferedReader(new InputStreamReader(fis, Charsets.UTF_8)); Document xmlDocument = saxBuilder.build(fis); xmlDocuments.add(xmlDocument); System.out.println("OK"); } return inferSchema(xmlDocuments, configuration); } else if (configuration.getWorkingFormat().equals("json")) { filenameFilter = FILE_NAME_FILTER_JSON_EXTENSION; List<File> jsonFiles = getInstanceFileNames(args, filenameFilter); List<JSONObject> jsonDocumentWithRootObjects = new ArrayList<>(jsonFiles.size()); List<JSONArray> jsonDocumentWithRootArrays = new ArrayList<>(jsonFiles.size()); for (int i = 0; i < jsonFiles.size(); i++) { File jsonFile = jsonFiles.get(i); String jsonString = Joiner.on(System.lineSeparator()) .join(Files.readAllLines(jsonFile.toPath())); JSONObject jsonObject = null; try { jsonObject = new JSONObject(jsonString); } catch (JSONException e) { } if (jsonObject != null) { jsonDocumentWithRootObjects.add(jsonObject); } else { JSONArray jsonArray = null; try { jsonArray = new JSONArray(jsonString); } catch (JSONException e) { } if (jsonArray != null) { jsonDocumentWithRootArrays.add(jsonArray); } else { throw new JSONException("Invalid JSON Document " + jsonFile); } } } return inferSchema(jsonDocumentWithRootObjects, jsonDocumentWithRootArrays, configuration); } else { throw new InvalidXSDConfigurationParameterException( "Unknown working format. Impossible to load files"); } } catch (IOException | JDOMException | RuntimeException e) { throw new XSDInferencerException(e); } }