下面列出了怎么用org.json.simple.JSONArray的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public JSONArray listUsers(Collection<String> keys, int from, int size){
//validate keys
keys.retainAll(ACCOUNT.allowedToShowAdmin);
if (keys.isEmpty()){
errorCode = 2;
return null;
}
JSONObject response = getDB().getDocuments(DB.USERS, "all", from, size, keys);
if (response == null){
errorCode = 4;
return null;
}
JSONArray hits = JSON.getJArray(response, new String[]{"hits", "hits"});
if (hits != null && !hits.isEmpty()){
JSONArray res = new JSONArray();
for (Object o : hits){
JSON.add(res, JSON.getJObject((JSONObject) o, "_source"));
}
return res;
}else{
errorCode = 4;
return new JSONArray();
}
}
public static ListResponse<AuditEntry> parseAuditEntries(JSONObject jsonObject)
{
List<AuditEntry> entries = new ArrayList<>();
JSONObject jsonList = (JSONObject) jsonObject.get("list");
assertNotNull(jsonList);
JSONArray jsonEntries = (JSONArray) jsonList.get("entries");
assertNotNull(jsonEntries);
for (int i = 0; i < jsonEntries.size(); i++)
{
JSONObject jsonEntry = (JSONObject) jsonEntries.get(i);
JSONObject entry = (JSONObject) jsonEntry.get("entry");
entries.add(parseAuditEntry(entry));
}
ExpectedPaging paging = ExpectedPaging.parsePagination(jsonList);
ListResponse<AuditEntry> resp = new ListResponse<AuditEntry>(paging, entries);
return resp;
}
public List<DockerContainer> getContainers() {
try {
JSONArray value = (JSONArray) doGetRequest("/containers/json?all=1",
Collections.singleton(HttpURLConnection.HTTP_OK));
List<DockerContainer> ret = new ArrayList<>(value.size());
for (Object o : value) {
JSONObject json = (JSONObject) o;
String id = (String) json.get("Id");
String image = (String) json.get("Image");
String name = null;
JSONArray names = (JSONArray) json.get("Names");
if (names != null && !names.isEmpty()) {
name = (String) names.get(0);
}
DockerContainer.Status status = DockerUtils.getContainerStatus((String) json.get("Status"));
ret.add(new DockerContainer(instance, id, image, name, status));
}
return ret;
} catch (DockerException ex) {
LOGGER.log(Level.INFO, null, ex);
}
return Collections.emptyList();
}
static public JSONObject createTopLevelJson() {
JSONObject topLevelJson = new JSONObject();
topLevelJson.put("geometries", new JSONArray());
topLevelJson.put("materials", new JSONArray());
/*
JSONObject models_json = new JSONObject();
models_json.put("uuid", UUID.randomUUID().toString());
models_json.put("type", "Group");
models_json.put("name", "Models");
//System.out.println(model_json.toJSONString());
JSONArray models_json_arr = new JSONArray();
models_json.put("children", models_json_arr);
topLevelJson.put("object", models_json);
*/
return topLevelJson;
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JSONObject getPluginData() {
JSONObject data = new JSONObject();
String pluginName = plugin.getDescription().getName();
String pluginVersion = plugin.getDescription().getVersion();
data.put("pluginName", pluginName); // Append the name of the plugin
data.put("pluginVersion", pluginVersion); // Append the version of the plugin
JSONArray customCharts = new JSONArray();
for (CustomChart customChart : charts) {
// Add the data of the custom charts
JSONObject chart = customChart.getRequestJsonObject();
if (chart == null) { // If the chart is null, we skip it
continue;
}
customCharts.add(chart);
}
data.put("customCharts", customCharts);
return data;
}
/**
* Check to see if the JSONArrays are different.
*
* @param previous The first JSONArray to check
* @param current The second JSONArray to check.
* @return True if the JSONArrays are different
*/
protected final boolean isDifferent(final JSONArray previous,
final JSONArray current) {
if (previous.size() != current.size()) {
return true;
}
for (int x = 0; x < previous.size(); x++) {
Object previousValue = previous.get(x);
Object currentValue = current.get(x);
if (compare(previousValue, currentValue)) {
return true;
}
}
return false;
}
@Override
protected JSONObject getChartData() {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
HashMap<String, Integer> map = getValues(new HashMap<>());
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JSONArray categoryValues = new JSONArray();
categoryValues.add(entry.getValue());
values.put(entry.getKey(), categoryValues);
}
data.put("values", values);
return data;
}
public Map<String, String> parseDatacenters() {
HashMap<String, String> dcNameType = new HashMap<String, String>();
try {
JSONObject doc = (JSONObject) JSONValue.parse(new FileReader(this.filename));
JSONArray datacenters = (JSONArray) doc.get("datacenters");
@SuppressWarnings("unchecked")
Iterator<JSONObject> iter = datacenters.iterator();
while(iter.hasNext()){
JSONObject node = iter.next();
String dcName = (String) node.get("name");
String type = (String) node.get("type");
dcNameType.put(dcName, type);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return dcNameType;
}
/**
* Returns meta-information of all stylesheets.
*
* @return meta-information of all stylesheets.
*/
public List<StyleSheetHeader> getAllStyleSheets() {
List<StyleSheetHeader> sheets = new ArrayList<StyleSheetHeader>();
Response response = transport.sendBlockingCommand(new Command("CSS.getAllStyleSheets")); // NOI18N
if (response != null) {
JSONObject result = response.getResult();
if (result == null) {
// CSS.getAllStyleSheets is not in the latest versions of the protocol
sheets = Collections.unmodifiableList(styleSheetHeaders);
} else {
JSONArray headers = (JSONArray)result.get("headers"); // NOI18N
for (Object o : headers) {
JSONObject header = (JSONObject)o;
sheets.add(new StyleSheetHeader(header));
}
}
}
return sheets;
}
protected void processPragmaDirective(long id, AST ast, JSONObject attributes) throws Exception {
JSONArray literals = (JSONArray)attributes.get("literals");
if (literals == null) {
throw new Exception("Pragma directive without literals attribute");
}
if (literals.size() < 1) {
throw new Exception("Pragma directive with empty literals list");
}
String type = (String)literals.get(0);
String args = null;
if (literals.size() > 1) {
args = "";
for (int i = 1; i < literals.size(); ++i) {
args += (String)literals.get(i);
}
}
ast.addInnerNode(new ASTPragmaDirective(id, type, args));
}
/**
* {@inheritDoc}
*/
@Override
public JSONArray getSignupMeetingsForContext(String siteId) {
JSONArray jsonMeetings = new JSONArray();
Collection<SignupMeeting> meetings = signupService.getAllSignupMeetings(siteId, getCurrentUserId());
String url = getUrlForTool(DateManagerConstants.COMMON_ID_SIGNUP);
String toolTitle = toolManager.getTool(DateManagerConstants.COMMON_ID_SIGNUP).getTitle();
for(SignupMeeting meeting : meetings) {
JSONObject mobj = new JSONObject();
mobj.put("id", meeting.getId());
mobj.put("title", meeting.getTitle());
mobj.put("due_date", formatToUserDateFormat(meeting.getEndTime()));
mobj.put("open_date", formatToUserDateFormat(meeting.getStartTime()));
mobj.put("tool_title", toolTitle);
mobj.put("url", url);
mobj.put("extraInfo", "false");
jsonMeetings.add(mobj);
}
return jsonMeetings;
}
@Test
public void setTimers() throws Exception {
final JSONBasicRollupsOutputSerializer serializer = new JSONBasicRollupsOutputSerializer();
final MetricData metricData = new MetricData(
FakeMetricDataGenerator.generateFakeTimerRollups(),
"unknown");
JSONObject metricDataJSON = serializer.transformRollupData(metricData, PlotRequestParser.DEFAULT_TIMER);
final JSONArray data = (JSONArray)metricDataJSON.get("values");
Assert.assertEquals(5, data.size());
for (int i = 0; i < data.size(); i++) {
final JSONObject dataJSON = (JSONObject)data.get(i);
Assert.assertNotNull(dataJSON.get("numPoints"));
Assert.assertNotNull(dataJSON.get("average"));
Assert.assertNotNull(dataJSON.get("rate"));
// bah. I'm too lazy to check equals.
}
}
/**
* filterクエリに複数の括弧を指定してフィルタリング後に特定のプロパティのみが取得できること.
*/
@Test
public final void filterクエリに複数の括弧を指定してフィルタリング後に特定のプロパティのみが取得できること() {
final String entity = "filterlist";
String query = "?\\$top=3&\\$skip=4&\\$select=datetime&"
+ "\\$filter=%28substringof%28%27string%27%2Cstring%29+and+%28boolean+eq+false"
+ "%29%29+or+%28int32+le+5000%29&\\$inlinecount=allpages&\\$orderby=__id+asc";
TResponse res = UserDataUtils.list(Setup.TEST_CELL_FILTER, "box", "odata", entity,
query, AbstractCase.MASTER_TOKEN_NAME, HttpStatus.SC_OK);
// レスポンスボディーが昇順に並んでいることのチェック
JSONObject jsonResp = res.bodyAsJson();
ArrayList<String> urilist = new ArrayList<String>();
int[] ids = {4, 5, 7 };
for (int idx : ids) {
urilist.add(UrlUtils.userData(Setup.TEST_CELL_FILTER, "box", "odata",
entity + String.format("('id_%04d')", idx)));
}
ODataCommon.checkCommonResponseUri(jsonResp, urilist);
JSONArray array = (JSONArray) ((JSONObject) jsonResp.get("d")).get("results");
for (Object element : array) {
JSONObject json = (JSONObject) element;
assertTrue(json.containsKey("datetime"));
assertFalse(json.containsKey("int32"));
}
}
/**
* Imports dataset.
*
* @throws java.io.IOException
*/
private static void dataSetImport() throws IOException, ParseException {
URL url = Resources.getResource(DATA_SET_NAME);
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader(url.getFile()));
JSONObject jsonObject = (JSONObject) obj;
String id = (String) jsonObject.get("id");
JSONObject metadata = (JSONObject) jsonObject.get("metadata");
JSONArray cantos = (JSONArray) jsonObject.get("cantos");
Key key = new Key(NAMESPACE_ENTITY, SET_NAME, id);
Bin binId = new Bin("id", id);
Bin binMetadata = new Bin("metadata", metadata);
Bin binCantos = new Bin("cantos", cantos);
aerospike.put(null, key, binId, binMetadata, binCantos);
aerospike.createIndex(null, NAMESPACE_ENTITY, SET_NAME, "id_idx", "id", IndexType.STRING);
Key key2 = new Key(NAMESPACE_CELL, SET_NAME, 3);
Bin bin_id = new Bin("_id", "3");
Bin bin_number = new Bin("number", 3);
Bin bin_text = new Bin("message", "new message test");
aerospike.put(null, key2, bin_id, bin_number, bin_text);
aerospike.createIndex(null, NAMESPACE_CELL, SET_NAME, "num_idx", "number", IndexType.NUMERIC);
aerospike.createIndex(null, NAMESPACE_CELL, SET_NAME, "_id_idx", "_id", IndexType.STRING);
}
Style(JSONObject style, String preferredId) {
if (preferredId != null) {
id = new StyleId(preferredId);
} else {
if (style.containsKey("styleId")) { // NOI18N
id = new StyleId((JSONObject)style.get("styleId")); // NOI18N
} else if (style.containsKey("styleSheetId")) { // NOI18N
id = new StyleId((String)style.get("styleSheetId")); // NOI18N
} else {
id = null;
}
}
JSONArray cssProperties = (JSONArray)style.get("cssProperties"); // NOI18N
properties = new ArrayList<Property>(cssProperties.size());
for (Object o : cssProperties) {
JSONObject cssProperty = (JSONObject)o;
Property property = new Property(cssProperty);
properties.add(property);
}
text = (String)style.get("cssText"); // NOI18N
if (style.containsKey("range")) { // NOI18N
range = new SourceRange((JSONObject)style.get("range")); // NOI18N
}
}
private JSONObject getBundle(String component, String locale, TranslationDTO allTranslationDTO) {
JSONArray array = allTranslationDTO.getBundles();
@SuppressWarnings("unchecked")
Iterator<JSONObject> objectIterator = array.iterator();
while(objectIterator.hasNext()) {
JSONObject object = objectIterator.next();
String fileLocale = (String) object.get(ConstantsKeys.lOCALE);
String fileComponent = (String) object.get(ConstantsKeys.COMPONENT);
if(locale.equals(fileLocale)&& component.equals(fileComponent)) {
return object;
}
}
return null;
}
private List<Group> parseGroups(JSONArray groupJson) {
List<Group> groups = new ArrayList<Group>(groupJson.size());
for (Object obj : groupJson) {
JSONObject groupObject = (JSONObject) obj;
String id = (String) groupObject.get("id");
String policy = (String) groupObject.get("policy");
List<Experiment> experiments = parseExperiments((JSONArray) groupObject.get("experiments"), id);
List<TrafficAllocation> trafficAllocations =
parseTrafficAllocation((JSONArray) groupObject.get("trafficAllocation"));
groups.add(new Group(id, policy, experiments, trafficAllocations));
}
return groups;
}
@Test
public void testIsProductionEndpointsInvalidJSON() throws Exception {
Log log = Mockito.mock(Log.class);
PowerMockito.mockStatic(LogFactory.class);
Mockito.when(LogFactory.getLog(Mockito.any(Class.class))).thenReturn(log);
API api = Mockito.mock(API.class);
Mockito.when(api.getEndpointConfig()).thenReturn("</SomeXML>");
Assert.assertFalse("Unexpected production endpoint found", APIUtil.isProductionEndpointsExists("</SomeXML>"));
JSONObject productionEndpoints = new JSONObject();
productionEndpoints.put("url", "https:\\/\\/localhost:9443\\/am\\/sample\\/pizzashack\\/v1\\/api\\/");
productionEndpoints.put("config", null);
JSONArray jsonArray = new JSONArray();
jsonArray.add(productionEndpoints);
Mockito.when(api.getEndpointConfig()).thenReturn(jsonArray.toJSONString());
Assert.assertFalse("Unexpected production endpoint found", APIUtil.isProductionEndpointsExists(jsonArray.toJSONString()));
}
@Override
protected JSONObject getChartData() {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
HashMap<String, Integer> map = getValues(new HashMap<String, Integer>());
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JSONArray categoryValues = new JSONArray();
categoryValues.add(entry.getValue());
values.put(entry.getKey(), categoryValues);
}
data.put("values", values);
return data;
}
private static JSONObject toJSONObject(Map<String, Object> map) {
JSONObject object = new JSONObject();
for (String key : map.keySet()) {
Object content = map.get(key);
if (content instanceof Collection) {
JSONArray array = new JSONArray();
array.addAll((Collection<?>) content);
object.put(key, array);
} else if (content instanceof Map) {
object.put(key, toJSONObject((Map<String, Object>) content));
} else {
object.put(key, content);
}
}
return object;
}
@Override
protected JSONObject getChartData() throws Exception {
JSONObject data = new JSONObject();
JSONObject values = new JSONObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JSONArray categoryValues = new JSONArray();
categoryValues.add(entry.getValue());
values.put(entry.getKey(), categoryValues);
}
data.put("values", values);
return data;
}
@SuppressWarnings("unchecked")
@Override
public JSONObject extract(boolean skipSensitive) {
JSONObject result = new JSONObject();
result.put(BUILD_VERSION, buildVersion);
result.put(SOURCE_REVISION, sourceRevision);
result.put(BUILD_DATE, buildDate);
result.put(SYSTEM_USER_NAME, systemUser);
result.put(SOURCE_URL, sourceUrl);
JSONArray apiVersionsArray = new JSONArray();
for (String version : supportedRestAPIVersions) {
apiVersionsArray.add(version);
}
result.put(SUPPORTED_API_VERSIONS, apiVersionsArray);
return result;
}
public static List<TransactionBean> fromJSONTransactions(JSONArray jtranss, ApplicationBean context)
{
List<TransactionBean> transs = new ArrayList<TransactionBean>();
for (Object jtrans : jtranss)
transs.add(fromJSONTransaction(new TransactionBean(), (JSONObject)jtrans, context));
return transs;
}
/**
* 自動生成された受信メッセージの削除.
* @param targetCell targetCell
* @param fromCellUrl fromCellUrl
* @param type type
* @param title title
* @param body body
*/
public static void deleteReceivedMessage(String targetCell,
String fromCellUrl,
String type,
String title,
String body) {
TResponse resReceivedList = null;
try {
resReceivedList = Http
.request("received-message-list.txt")
.with("cellPath", targetCell)
.with("token", AbstractCase.MASTER_TOKEN_NAME)
.with("query", "?\\$filter=From+eq+%27" + URLEncoder.encode(fromCellUrl, "UTF-8") + "%27+"
+ "and+Type+eq+%27" + URLEncoder.encode(type, "UTF-8") + "%27+"
+ "and+Title+eq+%27" + URLEncoder.encode(title, "UTF-8") + "%27")
.returns()
.debug();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JSONObject jsonBody = (JSONObject) resReceivedList.bodyAsJson().get("d");
if (jsonBody != null) {
JSONArray resultsList = (JSONArray) jsonBody.get("results");
for (int i = 0; i < resultsList.size(); i++) {
JSONObject results = (JSONObject) resultsList.get(i);
String id = (String) results.get("__id");
ReceivedMessageUtils.delete(AbstractCase.MASTER_TOKEN_NAME, targetCell, -1, id);
}
}
}
/**
* Get the real type of the object and make a dynamoDB element like "{"S":"some string"}".
* Note that this does a lot of unchecked class casting, so please test it thoroughly before using it!
* @param obj - object to cast, supported: (hashMap<String, Object>, ArrayList<Object>, String, Double, Integer, Boolean, Short, Float, Long)
* @return JSONObject in dynamoDB style (object can be empty)
*/
@SuppressWarnings("unchecked")
public static JSONObject typeConversionDynamoDB(Object obj){
JSONObject dyn = new JSONObject();
if (obj != null){
Class<?> c = obj.getClass();
//map
if (c.equals((new HashMap<String, Object>()).getClass())){
dyn = mapToJSON((HashMap<String, Object>) obj);
//list
}else if (c.equals(new ArrayList<Object>().getClass())){
dyn = listToJSON((ArrayList<Object>) obj);
//JSONArray list
}else if (c.equals(new JSONArray().getClass())){
dyn = jsonArrayToJSON((JSONArray) obj);
//string
}else if (c.equals(String.class)){
dyn.put("S", obj.toString());
//number
}else if (c.equals(Integer.class) || c.equals(Double.class) || c.equals(Long.class) || c.equals(Float.class) || c.equals(Short.class)){
dyn.put("N", obj.toString());
//boolean
}else if (c.equals(Boolean.class)){
dyn.put("BOOL", obj.toString());
//other is always string
}else{
dyn.put("S", obj.toString());
}
}
return dyn;
}
private JSONObject getJSONFileNode(JSONArray fileListJson, Integer fileID) {
for (val jsonNode : fileListJson) {
if (fileID.equals(((Long) ((JSONObject) jsonNode).get("id")).intValue())) {
return (JSONObject) jsonNode;
}
}
return new JSONObject();
}
public static List<ResourceBundle> restoreConfigParamBundles(JSONArray array) {
List<ResourceBundle> bundles = new LinkedList<ResourceBundle>();
for (Object item : array) {
bundles.add(restoreConfigParamBundle((JSONObject) item));
}
return bundles;
}
@Override
public void run() {
BowerExecutable executable = BowerExecutable.getDefault(project, false);
if (executable != null) {
JSONArray result = executable.search(searchTerm);
Library[] libraries = result == null ? null : parseSearchResult(result);
updateCache(searchTerm, libraries);
}
}
public UltimateFancy appendAtFirst(JSONObject json) {
JSONArray jarray = new JSONArray();
jarray.add(json);
jarray.addAll(getStoredElements());
this.constructor = jarray;
return this;
}
protected void processVariableDeclarationStatement(long id, AST ast, JSONObject attributes) throws Exception {
JSONArray assignments = (JSONArray)attributes.get("assignments");
ArrayList<Integer> assignmentIds = null;
if (assignments != null) {
assignmentIds = new ArrayList<Integer>();
for (int i = 0; i < assignments.size(); ++i) {
//if (assignments.get)
if (assignments.get(i) == null) {
// This is an empty slots, e.g. the first part in "var (,x) = (123, 456);"
assignmentIds.add(-1);
} else {
//int value = 0;
//Object object = (Object)assignments.get(i);
//if (object instanceof Integer) {
// value = (Integer)object;
//} else if (value instanceof Long) {
// value = (int)(Long)object;
//}
//assignments.add((Integer)assignments.get(i));
// ID typing and access are unclear - apparently sometimes int, sometimes long. Maybe
// we don't need IDs, so just mark this item as present (=1)
assignmentIds.add(1);
}
}
} else System.out.println(" !!!! no assignments");
ast.addInnerNode(new ASTVariableDeclarationStatement(id, assignmentIds));
}