当前位置: 首页>>代码示例>>Java>>正文


Java JSONObject类代码示例

本文整理汇总了Java中org.json.JSONObject的典型用法代码示例。如果您正苦于以下问题:Java JSONObject类的具体用法?Java JSONObject怎么用?Java JSONObject使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


JSONObject类属于org.json包,在下文中一共展示了JSONObject类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: removeNullFields

import org.json.JSONObject; //导入依赖的package包/类
/**
 * Remove 'null' fields from a JSONObject. This method calls itself recursively until all the
 * fields have been looked at.
 * TODO(mlamouri): move to some util class?
 */
private static void removeNullFields(Object object) throws JSONException {
    if (object instanceof JSONArray) {
        JSONArray array = (JSONArray) object;
        for (int i = 0; i < array.length(); ++i) removeNullFields(array.get(i));
    } else if (object instanceof JSONObject) {
        JSONObject json = (JSONObject) object;
        JSONArray names = json.names();
        if (names == null) return;
        for (int i = 0; i < names.length(); ++i) {
            String key = names.getString(i);
            if (json.isNull(key)) {
                json.remove(key);
            } else {
                removeNullFields(json.get(key));
            }
        }
    }
}
 
开发者ID:rkshuai,项目名称:chromium-for-android-56-debug-video,代码行数:24,代码来源:CastMessageHandler.java

示例2: decode

import org.json.JSONObject; //导入依赖的package包/类
public static Payload decode(String payload) throws JSONException {
    Builder builder = new Builder();
    JSONObject json = new JSONObject(payload);
    builder.setDst(json.getString(KEY_DST));
    builder.setSrc(json.getString(KEY_SRC));
    Type type;
    String s = json.getString(KEY_TYPE);
    if(Type.EVENT.name().equalsIgnoreCase(s)) {
        type = Type.EVENT;
    } else if(Type.REPLY.name().equalsIgnoreCase(s)) {
        type = Type.REPLY;
    } else {
        throw new JSONException("invalid type: " + s);
    }
    builder.setType(type);
    builder.setId(json.getInt(KEY_ID));
    try {
        builder.setStatus(Status.valueOf(json.optString(KEY_STATUS, "").toUpperCase()));
    } catch(IllegalArgumentException e) {
        builder.setStatus(Status.UNKNOWN);
    }
    builder.setMessage(json.getJSONObject(KEY_MESSAGE));
    return builder.build();
}
 
开发者ID:Orange-OpenSource,项目名称:OCast-Java,代码行数:25,代码来源:Payload.java

示例3: toMap

import org.json.JSONObject; //导入依赖的package包/类
public static Map<String, Object> toMap(JSONObject object) {
    Map<String, Object> map = new HashMap<>();
    
    String[] fields = JSONObject.getNames(object);
    
    for (String field : fields) {
        Object entry = object.get(field);
        
        if (entry instanceof JSONObject) {
            map.put(field, toMap((JSONObject) entry));
        } else if (entry instanceof JSONArray) {
            map.put(field, toCollection((JSONArray) entry));
        } else {
            map.put(field, entry);
        }
    }
    
    return map;
}
 
开发者ID:shawlaf,项目名称:Banmanager,代码行数:20,代码来源:JSONUtils.java

示例4: handleMessage

import org.json.JSONObject; //导入依赖的package包/类
public void handleMessage(Message msg) {
    super.handleMessage(msg);
    String smsg = msg.obj.toString();
    if (msg.what == 0) {
        try {
            LEYUApplication.dev_access_token = ((JSONObject) new JSONTokener(smsg)
                    .nextValue()).getString("access_token");
            LEYUApplication.set("leyu_dev_access_token", LEYUApplication.dev_access_token);
            LEYUApplication.this._callback.ReturnAccessToken(LEYUApplication
                    .dev_access_token);
        } catch (JSONException ex) {
            ex.printStackTrace();
            LEYUApplication.this._callback.onFailed(ex.getMessage());
        }
    } else if (msg.what == 1) {
        LEYUApplication.this._callback.OnCompleted(smsg);
    } else if (msg.what == 2) {
        LEYUApplication.this._callback.onFailed(smsg);
    }
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:21,代码来源:LEYUApplication.java

示例5: getPropertieSet

import org.json.JSONObject; //导入依赖的package包/类
public JSONObject getPropertieSet(String propname){
	if(this.target.has(propname)){
		if(this.target.getJSONObject(propname).getString("type").equals("set")){
			int selected = this.target.getJSONObject(propname).getInt("default");
			return this.target.getJSONObject(propname).getJSONArray("sets").getJSONObject(selected);
		}
		else{
			this.log.Warning("La propertie ("+propname+") especificada no corresponde al tipo llamado. Tipo declarado "+this.target.getJSONObject(propname).getString("type"), Error60.PROPERTIE_TYPE_INCORRECT);
		}
	}
	else
	{
		this.log.Warning("La propertie ("+propname+")especificada no existe, se envia valor null", Error60.PROPERTIE_NOT_SET);
		
	}
	return null;
}
 
开发者ID:acalvoa,项目名称:EARLGREY,代码行数:18,代码来源:Properties.java

示例6: doPost

import org.json.JSONObject; //导入依赖的package包/类
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp, String requestBody) throws IOException
{
    _logger.debug("entering");
    try
    {
        doPostHelp(req, resp, requestBody);
    }
    catch (Throwable e)
    {
        _logger.error(e.getMessage(), e);
        JSONObject responseBody = new ErrorJsonResponse("Unexpected exception during synthesis.");
        if(resp != null)
            resp.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
        writeObjectToServletOutputStream(responseBody, resp);
    }
    finally
    {
        _logger.debug("exiting");
    }
}
 
开发者ID:capergroup,项目名称:bayou,代码行数:22,代码来源:ApiSynthesisServlet.java

示例7: sendResult

import org.json.JSONObject; //导入依赖的package包/类
void sendResult(final JSONObject payload) {
    Assert.notNull(payload, "Payload must not be null!");
    if (!payload.has("id")) {
        throw new IllegalArgumentException("Payload must have an id!");
    }
    if (Looper.myLooper() == Looper.getMainLooper()) {
        webView.evaluateJavascript(String.format("MEIAM.handleResponse(%s);", payload), null);
    } else {
        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                webView.evaluateJavascript(String.format("MEIAM.handleResponse(%s);", payload), null);
            }
        });
    }
}
 
开发者ID:emartech,项目名称:android-mobile-engage-sdk,代码行数:17,代码来源:IamJsBridge.java

示例8: queueJumpToItem

import org.json.JSONObject; //导入依赖的package包/类
/**
 * Plays the item with {@code itemId} in the queue.
 * <p>
 * If {@code itemId} is not found in the queue, this method will report success without sending
 * a request to the receiver.
 *
 * @param itemId The ID of the item to which to jump.
 * @param customData Custom application-specific data to pass along with the request. May be
 *                   {@code null}.
 * @throws TransientNetworkDisconnectionException
 * @throws NoConnectionException
 * @throws IllegalArgumentException
 */
public void queueJumpToItem(int itemId, final JSONObject customData)
        throws TransientNetworkDisconnectionException, NoConnectionException,
        IllegalArgumentException {
    checkConnectivity();
    if (itemId == MediaQueueItem.INVALID_ITEM_ID) {
        throw new IllegalArgumentException("itemId is not valid");
    }
    if (mRemoteMediaPlayer == null) {
        LOGE(TAG, "Trying to jump in a queue with no active media session");
        throw new NoConnectionException();
    }
    mRemoteMediaPlayer
            .queueJumpToItem(mApiClient, itemId, customData).setResultCallback(
            new ResultCallback<MediaChannelResult>() {

                @Override
                public void onResult(MediaChannelResult result) {
                    for (VideoCastConsumer consumer : mVideoConsumers) {
                        consumer.onMediaQueueOperationResult(QUEUE_OPERATION_JUMP,
                                result.getStatus().getStatusCode());
                    }
                }
            });
}
 
开发者ID:SebastianRask,项目名称:Pocket-Plays-for-Twitch,代码行数:38,代码来源:VideoCastManager.java

示例9: getQuotes

import org.json.JSONObject; //导入依赖的package包/类
private List<Quote> getQuotes() {
  try {
    JSONArray array = new JSONArray(loadJSONFromAsset());
    List<Quote> quotes = new ArrayList<>();
    for (int i = 0; i < array.length(); i++) {
      JSONObject branchObject = array.getJSONObject(i);
      String quote = branchObject.getString("quote");
      String author = branchObject.getString("author");
      quotes.add(new Quote(author, quote));
    }
    return quotes;
  } catch (JSONException e) {
    Log.e(TAG, "getJSONFromAsset", e);
  }
  return null;
}
 
开发者ID:DevAhamed,项目名称:MultiViewAdapter,代码行数:17,代码来源:DataBindingActivity.java

示例10: write

import org.json.JSONObject; //导入依赖的package包/类
@Override
public String write(InitializrMetadata metadata, String appUrl) {
	JSONObject delegate = new JSONObject();
	links(delegate, metadata.getTypes().getContent(), appUrl);
	dependencies(delegate, metadata.getDependencies());
	type(delegate, metadata.getTypes());
	singleSelect(delegate, metadata.getPackagings());
	singleSelect(delegate, metadata.getJavaVersions());
	singleSelect(delegate, metadata.getLanguages());
	singleSelect(delegate, metadata.getEdorasoneVersions());
	text(delegate, metadata.getGroupId());
	text(delegate, metadata.getArtifactId());
	text(delegate, metadata.getVersion());
	text(delegate, metadata.getName());
	text(delegate, metadata.getShortName());
	text(delegate, metadata.getDescription());
	text(delegate, metadata.getPackageName());
	return delegate.toString();
}
 
开发者ID:rvillars,项目名称:edoras-one-initializr,代码行数:20,代码来源:InitializrMetadataV2JsonMapper.java

示例11: process

import org.json.JSONObject; //导入依赖的package包/类
@Override
public void process(HttpServletResponse response) throws Exception {
	MapMatchingRequest req = JsonMapMatchingRequestParser.parseFromRequestParams(_request);
	
	if (req == null)
		throw new StatusCodeException(StatusCode.BAD_REQUEST, MapMatchingErrorCodes.UNKNOWN, "MapMatchingRequest object is null.");
	
	if (MapMatchingServiceSettings.getMaximumLocations() > 0 && req.getCoordinates().length > MatrixServiceSettings.getMaximumLocations())
		throw new ParameterOutOfRangeException(MapMatchingErrorCodes.PARAMETER_VALUE_EXCEEDS_MAXIMUM, "sources/destinations", Integer.toString(req.getCoordinates().length), Integer.toString(MapMatchingServiceSettings.getMaximumLocations()));

	
	RouteResult result = RoutingProfileManager.getInstance().matchTrack(req);
	
	JSONObject json = null;
	
	String respFormat = _request.getParameter("format");
	if (Helper.isEmpty(respFormat) || "json".equalsIgnoreCase(respFormat))
		json = JsonMapMatchingResponseWriter.toJson(req, new RouteResult[] { result });
	else if ("geojson".equalsIgnoreCase(respFormat))
		json = JsonMapMatchingResponseWriter.toGeoJson(req, new RouteResult[] { result });
	
	ServletUtility.write(response, json, "UTF-8");
}
 
开发者ID:GIScience,项目名称:openrouteservice,代码行数:24,代码来源:JsonMapMatchingRequestProcessor.java

示例12: doInBackground

import org.json.JSONObject; //导入依赖的package包/类
@Override
protected List<HashMap<String, String>> doInBackground(
        String... jsonData) {

    List<HashMap<String, String>> places = null;
    PlaceJSONParser placeJsonParser = new PlaceJSONParser();

    try {
        jObject = new JSONObject(jsonData[0]);
        Log.v(TAG,jObject.toString());
        places = placeJsonParser.parse(jObject);
        page_token = placeJsonParser.getPageToken(jObject);

    } catch (Exception e) {
        Log.d("Exception", e.toString());
    }
    return places;
}
 
开发者ID:jorseph,项目名称:SearchRestaurant,代码行数:19,代码来源:MainActivity.java

示例13: FilterRule

import org.json.JSONObject; //导入依赖的package包/类
public FilterRule(@NonNull JSONObject rule) throws JSONException {
	name = rule.getString("name");
	ArrayList<String> packageNames = new ArrayList<>();
	for (int i = 0; i < rule.getJSONArray("packageNames").length(); i++) {
		try {
			packageNames.add(rule.getJSONArray("packageNames").getString(i));
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	this.packageNames = packageNames.toArray(this.packageNames);
	useDaytime = rule.getBoolean("useDaytime");
	if (useDaytime) {
		from = rule.getString("from");
		to = rule.getString("to");
	}
	identityID = rule.getLong("identityID");
	exec = rule.getString("exec");
}
 
开发者ID:SapuSeven,项目名称:NotiCap,代码行数:20,代码来源:FilterRule.java

示例14: getBody

import org.json.JSONObject; //导入依赖的package包/类
@Override
protected byte[] getBody(Context context) {

    byte[] array = new byte[0];

    JSONObject body = new JSONObject();
    try {
        body.put("network_id", params.getNetworkId());
        body.put("zone_id", params.getZoneId());
        body.put("user_id", params.getUserId());
        List<String> stringList = new ArrayList<>(Arrays.asList(params.getKeywords()));
        body.put("keywords", new JSONArray(stringList));
        if(params.getWidth() != null)
            body.put("width", params.getWidth());
        if(params.getHeight() != null)
            body.put("height", params.getHeight());

        array =  body.toString().getBytes("UTF-8");
    } catch (JSONException | UnsupportedEncodingException e) {
        e.printStackTrace();

    }

    return  array;

}
 
开发者ID:AdyoOrg,项目名称:adyo-android,代码行数:27,代码来源:GetPlacementRequest.java

示例15: a

import org.json.JSONObject; //导入依赖的package包/类
public static synchronized void a(b bVar) {
    synchronized (a.class) {
        if (!CommonUtils.isBlank(bVar.a())) {
            if (!bVar.a().equals(a())) {
                String str = bVar.a() + "`" + bVar.d();
                if (str != null) {
                    try {
                        str = SecurityUtils.encrypt(SecurityUtils.getSeed(), str);
                        JSONObject jSONObject = new JSONObject();
                        jSONObject.put("device", str);
                        PublicStorage.writeDataToPublicArea("deviceid_v2", jSONObject.toString());
                    } catch (Exception e) {
                    }
                }
            }
        }
    }
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:19,代码来源:a.java


注:本文中的org.json.JSONObject类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。