下面列出了怎么用org.json.JSONObject的API类实例代码及写法,或者点击链接到github查看源代码。
JSONObject toJson() {
JSONObject response = new JSONObject();
try {
response.put("jsonrpc", "2.0");
if (error != null)
response.put("error", error);
else if (result != null)
response.put("result", result);
else
throw new JSONException("error and result are null");
response.put("id", id);
return response;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public void from(Object obj) {
if (obj != null) {
if (obj instanceof JSONObject) {
JSONObject result = (JSONObject) obj;
this.rowkey = result.optString("rowkey");
this.count = result.optLong("count");
this.startTime = result.optString("startTime");
this.endTime = result.optString("endTime");
this.exchange.copyFrom(result.opt("exchange"));
this.exchangeRate = result.optDouble("exchangeRate");
this.total = result.optDouble("total");
JSONArray arrays = result.optJSONArray("components");
if (arrays != null) {
int size = arrays.length();
for (int i = 0; i < size; i++) {
MarketComponent marketComponent = new MarketComponent();
marketComponent.from(arrays.getJSONObject(i));
components.add(marketComponent);
}
}
}
}
}
public static Date getDate(JSONObject json) throws ParseException
{
if(json == null)
{
return null;
}
String dateTime = json.optString(DATE_TIME);
if(dateTime == null)
{
return null;
}
String format = json.optString(FORMAT);
if(format!= null && ISO8601.equals(format) == false)
{
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.parse(dateTime);
}
return ISO8601DateFormat.parse(dateTime);
}
public void sendAddressHistory(StratumConnection conn, Object request_id, ByteString scripthash, boolean include_confirmed, boolean include_mempool)
{
Subscriber sub = new Subscriber(conn, request_id);
try
{
JSONObject reply = sub.startReply();
reply.put("result", getScriptHashHistory(scripthash,include_confirmed,include_mempool));
sub.sendReply(reply);
}
catch(org.json.JSONException e)
{
throw new RuntimeException(e);
}
}
protected URI getPictureUriOfGraphObject(T graphObject) {
String uri = null;
Object o = graphObject.getProperty(PICTURE);
if (o instanceof String) {
uri = (String) o;
} else if (o instanceof JSONObject) {
ItemPicture itemPicture = GraphObject.Factory.create((JSONObject) o).cast(ItemPicture.class);
ItemPictureData data = itemPicture.getData();
if (data != null) {
uri = data.getUrl();
}
}
if (uri != null) {
try {
return new URI(uri);
} catch (URISyntaxException e) {
}
}
return null;
}
@Override
Object toJSON(){
if(!selfie && !translation && !nativeNames)
return type;
try{
JSONObject o=new JSONObject();
o.put("type", type);
if(selfie)
o.put("selfie", true);
if(translation)
o.put("translation", true);
if(nativeNames)
o.put("native_names", true);
return o;
}catch(JSONException ignore){}
return null;
}
@Test
public void attributeReplacementTest() throws Exception {
Context context = InstrumentationRegistry.getTargetContext();
AssetManager assetManager = context.getAssets();
InputStream inputStream = assetManager.open("common.xml");
XmlToJson xmlToJson = new XmlToJson.Builder(inputStream, null)
.setAttributeName("/library/book/id", "attributeReplacement")
.build();
inputStream.close();
JSONObject result = xmlToJson.toJson();
JSONObject library = result.getJSONObject("library");
JSONArray books = library.getJSONArray("book");
assertEquals(books.length(), 2);
for (int i = 0; i < books.length(); ++i) {
JSONObject book = books.getJSONObject(i);
book.getInt("attributeReplacement");
}
}
protected static List<ForwardInfo> loadForwardInfo(Context context) {
List<ForwardInfo> arrayList = new ArrayList<>();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
String jsonString = settings.getString("port_forward_json", "");
if(jsonString.isEmpty()) return arrayList;
try {
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
arrayList.add(ForwardInfo.getForwardInfo(obj));
}
} catch (JSONException e) {
e.printStackTrace();
}
return arrayList;
}
private boolean needPermission(String nativeURL, int permissionType) throws JSONException {
JSONObject j = requestAllPaths();
ArrayList<String> allowedStorageDirectories = new ArrayList<String>();
allowedStorageDirectories.add(j.getString("applicationDirectory"));
allowedStorageDirectories.add(j.getString("applicationStorageDirectory"));
if(j.has("externalApplicationStorageDirectory")) {
allowedStorageDirectories.add(j.getString("externalApplicationStorageDirectory"));
}
if(permissionType == READ && hasReadPermission()) {
return false;
}
else if(permissionType == WRITE && hasWritePermission()) {
return false;
}
// Permission required if the native url lies outside the allowed storage directories
for(String directory : allowedStorageDirectories) {
if(nativeURL.startsWith(directory)) {
return false;
}
}
return true;
}
public PluginResult requestAd(JSONObject options, CallbackContext callbackContext) {
CordovaInterface cordova = plugin.cordova;
plugin.config.setInterstitialOptions(options);
if (interstitialAd == null) {
callbackContext.error("interstitialAd is null, call createInterstitialView first");
return null;
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (interstitialAd == null) {
return;
}
interstitialAd.loadAd(plugin.buildAdRequest());
delayCallback.success();
}
});
return null;
}
/**
* logo商标识别—添加接口
* 使用入库接口请先在[控制台](https://console.bce.baidu.com/ai/#/ai/imagerecognition/overview/index)创建应用并申请建库,建库成功后方可正常使用。
*
* @param image - 二进制图像数据
* @param brief - brief,检索时带回。此处要传对应的name与code字段,name长度小于100B,code长度小于150B
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* @return JSONObject
*/
public JSONObject logoAdd(byte[] image, String brief, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
request.addBody("brief", brief);
if (options != null) {
request.addBody(options);
}
request.setUri(ImageClassifyConsts.LOGO_ADD);
postOperation(request);
return requestServer(request);
}
@Override
public void load(JSONObject object) throws JSONException {
super.load(object);
name = getString(object, "name");
JSONObject topic = object.getJSONArray("topics").getJSONObject(0);
numberOfOpenSuggestions = topic.getInt("open_suggestions_count");
numberOfVotesAllowed = topic.getInt("votes_allowed");
categories = deserializeList(topic, "categories", Category.class);
if (categories == null)
categories = new ArrayList<Category>();
}
private JSONObject parseReferenceLine(String line) {
// The JSON object does not contain type information. We have to parse
// by hand.
// line format "type0.type1.type2.source=destination0,destination1,
// ...,destinationN
JSONObject answer = new JSONObject();
String[] split = line.split("\\.");
answer.put("type", split[0] + "." + split[1] + "." + split[2]);
String[] addresses = split[3].split("=");
answer.put("address", Long.decode(addresses[0]));
answer.put("locations", new JSONArray(
Arrays.stream(addresses[1].split(",")).map(Long::decode)
.toArray()));
return answer;
}
static WebRequest getPostGitRemoteRequest(String location, String srcRef, boolean tags, boolean force) throws JSONException, UnsupportedEncodingException {
String requestURI = toAbsoluteURI(location);
JSONObject body = new JSONObject();
if (srcRef != null)
body.put(GitConstants.KEY_PUSH_SRC_REF, srcRef);
body.put(GitConstants.KEY_PUSH_TAGS, tags);
body.put(GitConstants.KEY_FORCE, force);
WebRequest request = new PostMethodWebRequest(requestURI, IOUtilities.toInputStream(body.toString()), "UTF-8");
request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
setAuthentication(request);
return request;
}
public void importData(JSONArray array){
SQLiteDatabase db = this.getWritableDatabase();
try {
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
ContentValues values = new ContentValues();
values.put(BOOK_NAME, row.getString("BOOK_NAME"));
values.put(BOOK_HEARD, row.getString("BOOK_HEARD"));
values.put(BOOK_DATE, row.getString("BOOK_DATE"));
db.insertWithOnConflict(TABLE_HEARD_BOOKS, null, values, SQLiteDatabase.CONFLICT_REPLACE);
}
}catch(Exception e){ }
}
@Override
protected JSONObject getExpectedParameters(int sdlVersion) {
JSONObject result = new JSONObject();
try {
result.put(DeleteWindow.KEY_WINDOW_ID, Test.GENERAL_INT);
} catch (JSONException e) {
fail(Test.JSON_FAIL);
}
return result;
}
private String getResponse(Currency fromCurrency, Currency toCurrency) throws Exception {
String url = buildUrl(fromCurrency, toCurrency);
Log.i(TAG, url);
JSONObject jsonObject = client.getAsJson(url);
Log.i(TAG, jsonObject.getString(toCurrency.name));
return jsonObject.getString(toCurrency.name);
}
@Override
public void run() {
if (PermissionChecker.hasExtStoragePerm(_context)) {
if (MainActivity.LOCAL_ONLY_MODE || MainActivity.DISABLE_ONLINE_ASSETS) {
return;
}
AppCast.ASSET_DOWNLOAD_REQUEST.send(_context, ASSET_DOWNLOAD_REQUEST__CHECKING);
String apiJsonS = NetworkUtils.performCall(URL_API, NetworkUtils.GET);
try {
JSONObject apiJson = new JSONObject(apiJsonS);
String lastUpdate = apiJson.getString("pushed_at");
int datesubstrindex = lastUpdate.indexOf(":", lastUpdate.indexOf(":") + 1);
Date date = FORMAT_MINUTE.parse(lastUpdate.substring(0, datesubstrindex));
if (date.after(_appSettings.getLastAssetArchiveDate())) {
_appSettings.setLastArchiveCheckDate(new Date(System.currentTimeMillis()));
if (!_doDownload) {
AppCast.ASSET_DOWNLOAD_REQUEST.send(_context, ASSET_DOWNLOAD_REQUEST__DO_DOWNLOAD_ASK);
} else {
doDownload(date);
new LoadAssetsThread(_context).start();
}
}
return;
} catch (JSONException | ParseException e) {
e.printStackTrace();
}
}
AppCast.ASSET_DOWNLOAD_REQUEST.send(_context, ASSET_DOWNLOAD_REQUEST__FAILED);
}
void post(Activity activity, final ShareObj obj) {
mWbLoginHelper.justAuth(activity, new WbAuthListenerImpl() {
@Override
public void onSuccess(final Oauth2AccessToken token) {
Task.callInBackground(() -> {
Map<String, String> params = new HashMap<>();
params.put("access_token", token.getToken());
params.put("status", obj.getSummary());
return _SocialSdk.getInst().getRequestAdapter().postData("https://api.weibo.com/2/statuses/share.json", params, "pic", obj.getThumbImagePath());
}).continueWith(task -> {
if (task.isFaulted() || TextUtils.isEmpty(task.getResult())) {
throw SocialError.make(SocialError.CODE_PARSE_ERROR, "open api 分享失败 " + task.getResult(), task.getError());
} else {
JSONObject jsonObject = new JSONObject(task.getResult());
if (jsonObject.has("id") && jsonObject.get("id") != null) {
mPlatform.onShareSuccess();
return true;
} else {
throw SocialError.make(SocialError.CODE_PARSE_ERROR, "open api 分享失败 " + task.getResult());
}
}
}, Task.UI_THREAD_EXECUTOR).continueWith(task -> {
if (task != null && task.isFaulted()) {
Exception error = task.getError();
if (error instanceof SocialError) {
mPlatform.onShareFail((SocialError) error);
} else {
mPlatform.onShareFail(SocialError.make(SocialError.CODE_REQUEST_ERROR, "open api 分享失败", error));
}
}
return true;
}, Task.UI_THREAD_EXECUTOR);
}
});
}
public void handleResult(Activity activity, ParseResultEntity resultEntity) {
LogInfo.log("lxx", "text: " + resultEntity.getText());
HashMap<String, String> qrCodeResult = new HashMap();
qrCodeResult.put("string", resultEntity.getText());
try {
jsCallBack(jsInBean, new JSONObject(qrCodeResult).toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
activity.finish();
}
}
public static Account parseJson (final JSONObject json) throws JSONException {
if (json == null) return null;
final String id = json.getString(KEY_ID);
final AccountProvider provider = AccountProvider.parse(json.getString(KEY_PROVIDER));
Account account;
switch (provider) {
case TWITTER:
account = parseTwitterAccount(json, id);
break;
case MASTODON:
account = parseMastodonAccount(json, id);
break;
case SUCCESSWHALE:
account = parseUsernamePasswordLikeAccount(json, id, AccountProvider.SUCCESSWHALE);
break;
case INSTAPAPER:
account = parseUsernamePasswordLikeAccount(json, id, AccountProvider.INSTAPAPER);
break;
case HOSAKA:
account = parseUsernamePasswordLikeAccount(json, id, AccountProvider.HOSAKA);
break;
case BUFFER:
account = parseBufferAccount(json, id);
break;
default:
throw new IllegalArgumentException("Unknown provider: " + provider);
}
return account;
}
private JSONObject getEntry(String name, int expectedStatus) throws Exception
{
Response response = sendRequest(new GetRequest(URL_EVENT_BASE + name), expectedStatus);
if (expectedStatus == Status.STATUS_OK)
{
JSONObject result = validateAndParseJSON(response.getContentAsString());
return result;
}
else
{
return null;
}
}
/**
* Tests a valid JSON construction of this RPC message.
*/
public void testJsonConstructor () {
JSONObject commandJson = JsonFileReader.readId(this.mContext, getCommandType(), getMessageType());
assertNotNull(Test.NOT_NULL, commandJson);
try {
Hashtable<String, Object> hash = JsonRPCMarshaller.deserializeJSONObject(commandJson);
ReadDID cmd = new ReadDID(hash);
JSONObject body = JsonUtils.readJsonObjectFromJsonObject(commandJson, getMessageType());
assertNotNull(Test.NOT_NULL, body);
// Test everything in the json body.
assertEquals(Test.MATCH, JsonUtils.readStringFromJsonObject(body, RPCMessage.KEY_FUNCTION_NAME), cmd.getFunctionName());
assertEquals(Test.MATCH, JsonUtils.readIntegerFromJsonObject(body, RPCMessage.KEY_CORRELATION_ID), cmd.getCorrelationID());
JSONObject parameters = JsonUtils.readJsonObjectFromJsonObject(body, RPCMessage.KEY_PARAMETERS);
assertEquals(Test.MATCH, JsonUtils.readIntegerFromJsonObject(parameters, ReadDID.KEY_ECU_NAME), cmd.getEcuName());
List<Integer> didLocationList = JsonUtils.readIntegerListFromJsonObject(parameters, ReadDID.KEY_DID_LOCATION);
List<Integer> testLocationList = cmd.getDidLocation();
assertEquals(Test.MATCH, didLocationList.size(), testLocationList.size());
assertTrue(Test.TRUE, Validator.validateIntegerList(didLocationList, testLocationList));
} catch (JSONException e) {
fail(Test.JSON_FAIL);
}
}
private void handleSubscriptionConfirmation(HttpServletRequest request,
HttpServletResponse response) throws IOException {
try {
String source = readBody(request);
log.debug("Subscription confirmation:\n" + source);
JSONObject confirmation = new JSONObject(source);
if (validSignature(source, confirmation)) {
URL subscribeUrl = new URL(
confirmation.getString("SubscribeURL"));
HttpURLConnection http = (HttpURLConnection) subscribeUrl
.openConnection();
http.setDoOutput(false);
http.setDoInput(true);
StringBuilder buffer = new StringBuilder();
byte[] buf = new byte[4096];
while ((http.getInputStream().read(buf)) >= 0) {
buffer.append(new String(buf));
}
log.debug("SubscribeURL response:\n" + buffer.toString());
}
response.setStatus(HttpServletResponse.SC_OK);
} catch (JSONException e) {
throw new IOException(e.getMessage(), e);
}
}
/**
* Sets account name and container name in headers.
* @param headers the {@link JSONObject} where the headers should be set.
* @param targetAccountName sets the {@link RestUtils.Headers#TARGET_ACCOUNT_NAME} header. Can be {@code null}.
* @param targetContainerName sets the {@link RestUtils.Headers#TARGET_CONTAINER_NAME} header. Can be {@code null}.
* @throws IllegalArgumentException if {@code headers} is null.
* @throws JSONException
*/
private void setAccountAndContainerHeaders(JSONObject headers, String targetAccountName, String targetContainerName)
throws JSONException {
if (headers != null) {
if (targetAccountName != null) {
headers.put(RestUtils.Headers.TARGET_ACCOUNT_NAME, targetAccountName);
}
if (targetContainerName != null) {
headers.put(RestUtils.Headers.TARGET_CONTAINER_NAME, targetContainerName);
}
} else {
throw new IllegalArgumentException("Some required arguments are null. Cannot set ambry headers");
}
}
@Test
public void testJsonToAttributes_empty() throws Exception {
JSONObject jsonObj = new JSONObject();
Attributes attrs = AttributesUtil.jsonToAttributes(jsonObj);
assertThat(attrs).isEqualTo(new Attributes());
}
@NonNull
private JSONObject createOtherBottomTabs() throws JSONException {
return new JSONObject()
.put("currentTabId", BOTTOM_TABS_CURRENT_TAB_ID)
.put("currentTabIndex", BOTTOM_TABS_CURRENT_TAB_INDEX)
.put("visible", BOTTOM_TABS_VISIBLE)
.put("animate", BOTTOM_TABS_ANIMATE.get())
.put("tabBadge", BOTTOM_TABS_BADGE);
}
/**
* - resets the js flag which is set when the user changes form data and is checked when an other link is clicked.(to prevent form data loss).<br>
*
* @return the command
*/
public static Command createPrepareClientCommand(String businessControlPath) {
JSONObject root = new JSONObject();
try {
root.put("bc", businessControlPath == null ? "" : businessControlPath);
} catch (JSONException e) {
throw new AssertException("wrong data put into json object", e);
}
Command c = new Command(6);
c.setSubJSON(root);
return c;
}
/**
* 通用文字识别(高精度版)接口
* 用户向服务请求识别某张图中的所有文字,相对于通用文字识别该产品精度更高,但是识别耗时会稍长。
*
* @param image - 二进制图像数据
* @param options - 可选参数对象,key: value都为string类型
* options - options列表:
* detect_direction 是否检测图像朝向,默认不检测,即:false。朝向是指输入图像是正常方向、逆时针旋转90/180/270度。可选值包括:<br>- true:检测朝向;<br>- false:不检测朝向。
* probability 是否返回识别结果中每一行的置信度
* @return JSONObject
*/
public JSONObject basicAccurateGeneral(byte[] image, HashMap<String, String> options) {
AipRequest request = new AipRequest();
preOperation(request);
String base64Content = Base64Util.encode(image);
request.addBody("image", base64Content);
if (options != null) {
request.addBody(options);
}
request.setUri(OcrConsts.ACCURATE_BASIC);
postOperation(request);
return requestServer(request);
}
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> post(@RequestBody String inputString, @RequestParam(required = false) Integer gcpLength) {
Configuration.logger.info(" EPCIS Masterdata Document Capture Started.... ");
JSONObject retMsg = new JSONObject();
if (Configuration.isCaptureVerfificationOn == true) {
InputStream validateStream = CaptureUtil.getXMLDocumentInputStream(inputString);
// Parsing and Validating data
boolean isValidated = CaptureUtil.validate(validateStream,
Configuration.wsdlPath + "/EPCglobal-epcis-masterdata-1_2.xsd");
if (isValidated == false) {
return new ResponseEntity<>(new String("Error: EPCIS Masterdata Document is not validated"),
HttpStatus.BAD_REQUEST);
}
}
InputStream epcisStream = CaptureUtil.getXMLDocumentInputStream(inputString);
EPCISMasterDataDocumentType epcisMasterDataDocument = JAXB.unmarshal(epcisStream,
EPCISMasterDataDocumentType.class);
CaptureService cs = new CaptureService();
retMsg = cs.capture(epcisMasterDataDocument, gcpLength);
Configuration.logger.info(" EPCIS Masterdata Document : Captured ");
if (retMsg.isNull("error") == true)
return new ResponseEntity<>(retMsg.toString(), HttpStatus.OK);
else
return new ResponseEntity<>(retMsg.toString(), HttpStatus.BAD_REQUEST);
}