Java 类org.json.simple.JsonArray 实例源码

项目:alvisnlp    文件:GeniaJSONReader.java   
private void fillAnnotations(@SuppressWarnings("unused") Logger logger, Section sec, JSONObject json, Map<String,Element> eltMap) {
    JSONArray catanns = (JSONArray) json.get("catanns");
    if (catanns == null) {
        return;
    }
    Layer annotations = sec.ensureLayer(annotationsLayerName);
    for (Object o : catanns) {
        JSONObject ca = (JSONObject) o;
        String id = (String) ca.get("id");
        JSONObject span = (JSONObject) ca.get("span");
        int begin = (int) (long) span.get("begin");
        int end = (int) (long) span.get("end");
        String category = (String) ca.get("category");
        Layer layer = sec.ensureLayer(category);
        Annotation a = new Annotation(this, layer, begin, end);
        annotations.add(a);
        a.addFeature("id", id);
        a.addFeature("category", category);
        eltMap.put(id, a);
    }
}
项目:hadoop    文件:FSOperations.java   
/** Converts an <code>AclStatus</code> object into a JSON object.
 *
 * @param aclStatus AclStatus object
 *
 * @return The JSON representation of the ACLs for the file
 */
@SuppressWarnings({"unchecked"})
private static Map<String,Object> aclStatusToJSON(AclStatus aclStatus) {
  Map<String,Object> json = new LinkedHashMap<String,Object>();
  Map<String,Object> inner = new LinkedHashMap<String,Object>();
  JSONArray entriesArray = new JSONArray();
  inner.put(HttpFSFileSystem.OWNER_JSON, aclStatus.getOwner());
  inner.put(HttpFSFileSystem.GROUP_JSON, aclStatus.getGroup());
  inner.put(HttpFSFileSystem.ACL_STICKY_BIT_JSON, aclStatus.isStickyBit());
  for ( AclEntry e : aclStatus.getEntries() ) {
    entriesArray.add(e.toString());
  }
  inner.put(HttpFSFileSystem.ACL_ENTRIES_JSON, entriesArray);
  json.put(HttpFSFileSystem.ACL_STATUS_JSON, inner);
  return json;
}
项目:Cognizant-Intelligent-Test-Scripter    文件:Performance.java   
@SuppressWarnings("rawtypes")
private void createHar(String pt, String rt) {
    Har<String, Log> har = new Har<>();
    Page p = new Page(pt, har.pages());
    har.addPage(p);
    for (Object res : (JSONArray) JSONValue.parse(rt)) {
        JSONObject jse = (JSONObject) res;
        if (jse.size() > 14) {
            Entry e = new Entry(jse.toJSONString(), p);
            har.addEntry(e);
        }
    }
    har.addRaw(pt, rt);
    Control.ReportManager.addHar(har, (TestCaseReport) Report,
            escapeName(Data));
}
项目:alfresco-remote-api    文件:RestApiUtil.java   
/**
 * Parses the alfresco REST API response for a collection of entries.
 * Basically, it looks for the {@code list} JSON object, then it uses
 * {@literal Jackson} to convert the list's entries to their corresponding
 * POJOs based on the given {@code clazz}.
 * 
 * @param jsonObject the {@code JSONObject} derived from the response
 * @param clazz the class which represents the JSON payload
 * @return list of POJOs of the given {@code clazz} type
 * @throws Exception
 */
public static <T> List<T> parseRestApiEntries(JSONObject jsonObject, Class<T> clazz) throws Exception
{
    assertNotNull(jsonObject);
    assertNotNull(clazz);

    List<T> models = 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);
        T pojoModel = parseRestApiEntry(jsonEntry, clazz);
        models.add(pojoModel);
    }

    return models;
}
项目:RNNavitiaSDK    文件:MapUtil.java   
public static Map<String, Object> toMap(JSONObject jsonObject) throws JSONException {
    Map<String, Object> map = new HashMap<>();

    for (Object key : jsonObject.keySet()) {
        Object value = jsonObject.get(key);

        if (value instanceof JSONObject) {
            value = MapUtil.toMap((JSONObject) value);
        }
        if (value instanceof JSONArray) {
            value = ArrayUtil.toArray((JSONArray) value);
        }

        map.put(String.valueOf(key), value);
    }

    return map;
}
项目:JavaShell    文件:Metrics.java   
@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;
}
项目:personium-core    文件:Setup.java   
/**
 * すべてのEntityTypeのDELETE.
  * @param path
 *            コレクションパス
 * @param cellPath
 *            セル名
 * @return レスポンス
 */
public static TResponse allEntityTypeDelete(final String path, final String cellPath) {

    // EntityType全件取得
    TResponse res = Http.request("box/entitySet-query.txt").with("cellPath", cellPath).with("odataSvcPath", path)
            .with("token", AbstractCase.MASTER_TOKEN_NAME).with("accept", MediaType.APPLICATION_JSON).returns();

    JSONObject d = (JSONObject) res.bodyAsJson().get("d");
    if (d != null) {
        JSONArray results = (JSONArray) d.get("results");
        for (Object result : results) {
            JSONObject account = (JSONObject) result;
            String entityName = (String) account.get("Name");
            entityTypeDelete(path, entityName, cellPath, TEST_BOX1);
        }
    }
    return res;
}
项目:keywordEntityApiRankService    文件:DandelionAPI.java   
/**
 * Implemented receiveGET from Interface interfaceAPI (see for more details)
 *
 * @throws IOException    IO Error
 * @throws ParseException Parse Error
 */
public void receiveGET () throws IOException, ParseException {
    JSONArray JSONArray = readResponseJSON(API_IDENTIFIER, EntityUtils.toString(httpEntity, "UTF-8"), "annotations");

    if (JSONArray != null) {
        for (Object aJSONArray : JSONArray) {

            JSONObject object = (JSONObject) aJSONArray;
            ResponseEntry entity = new ResponseEntry();

            String s = (String) object.get("spot");
            s = addEntity(s);

            // Add Entity only if it is new and has not been added before
            if (s != null) {
                entity.setEntry(s);
                entity.setConfidence((Double) object.get("confidence"));
                foundEntryList.add(entity);
            }
        }

        // Sort the Array List Entities from A to Z
        Collections.sort(foundEntryList, new SortResponseEntity());
    }
}
项目:legendarybot    文件:IlvlCommand.java   
public long getM5(String json) throws ParseException {
    long m5 = 0;
    if (json != null) {
        JSONParser parser = new JSONParser();
        JSONObject battleNetCharacter = (JSONObject) parser.parse(json);
        JSONObject achivements = (JSONObject) battleNetCharacter.get("achievements");
        JSONArray criteriaObject = (JSONArray) achivements.get("criteria");
        int criteriaNumber = -1;
        for (int i = 0; i < criteriaObject.size(); i++) {
            if ((long)criteriaObject.get(i) == 33097) {
                criteriaNumber = i;
            }
        }

        if (criteriaNumber != -1) {
            m5 = (long) ((JSONArray)achivements.get("criteriaQuantity")).get(criteriaNumber);
            if (m5 >= 1) {
                m5 += 1;
            }
        }
    }
    return m5;
}
项目:Minecordbot    文件:Metrics.java   
/**
 * 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;
}
项目:Cognizant-Intelligent-Test-Scripter    文件:HarCompareHandler.java   
static Object getHars(File p, String page) {
    JSONArray dataset = new JSONArray();
    try {
        File[] list = p.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.getName().endsWith(".har");
            }
        });
        if (list != null) {
            for (File f : list) {
                JSONObject har = new JSONObject();
                har.put("name", f.getName().substring(0, f.getName().length() - 4));
                har.put("loc", f.getName());
                har.put("pageName", page);
                dataset.add(har);
            }
        }
    } catch (Exception ex) {
        LOG.log(Level.WARNING, "Error while reading report history", ex);
    }

    return dataset;
}
项目:UltimateSpawn    文件:Metrics.java   
/**
    * Gets the plugin specific data.
    * This method is called using Reflection.
    *
    * @return The plugin specific data.
    */
   @SuppressWarnings("unchecked")
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;
   }
项目:incubator-netbeans    文件:CSS.java   
private Map<String,PropertyInfo> loadSupportedProperties() {
    Map<String,PropertyInfo> map = new HashMap<>();
    try (InputStream stream = getClass().getResourceAsStream("Longhands.properties"); ) { // NOI18N
        Properties properties = new Properties();
        properties.load(stream);
        for(String name: properties.stringPropertyNames()) {
            StringTokenizer tokenizer = new StringTokenizer(properties.getProperty(name), ","); // NOI18N
            JSONArray longhands = new JSONArray();
            while (tokenizer.hasMoreTokens()) {
                String longhand = tokenizer.nextToken();
                longhands.add(longhand);
            }
            JSONObject json = new JSONObject();
            json.put("name", name); // NOI18N
            json.put("longhands", longhands); // NOI18N
            map.put(name, new PropertyInfo(json));
        }
    } catch (IOException ioex) {
        Logger.getLogger(CSS.class.getName()).log(Level.INFO, null, ioex);
    }
    return map;
}
项目:incubator-netbeans    文件:Debugger.java   
private JSONArray normalizeStackTrace(JSONArray callStack) {
    JSONArray res = new JSONArray();
    for (Object o : callStack) {
        JSONObject cf = (JSONObject)o;
        JSONObject ncf = new JSONObject();
        ncf.put("lineNumber", ((JSONObject)cf.get("location")).get("lineNumber"));
        ncf.put("columnNumber", ((JSONObject)cf.get("location")).get("columnNumber"));
        ncf.put("function", cf.get("functionName"));
        Script sc = getScript((String)((JSONObject)(cf.get("location"))).get("scriptId"));
        if (sc == null) {
            continue;
        }
        ncf.put("script", sc.getURL());
        res.add(ncf);
    }
    return res;
}
项目:skript-hack    文件:Metrics.java   
@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;
}
项目:NeuralNetworkAPI    文件:Metrics.java   
@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;
}
项目:EpicBanRequests    文件:Metrics.java   
@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;
}
项目:hadoop    文件:FSOperations.java   
/**
 * Converts xAttrs to a JSON object.
 *
 * @param xAttrs file xAttrs.
 * @param encoding format of xattr values.
 *
 * @return The JSON representation of the xAttrs.
 * @throws IOException 
 */
@SuppressWarnings({"unchecked", "rawtypes"})
private static Map xAttrsToJSON(Map<String, byte[]> xAttrs, 
    XAttrCodec encoding) throws IOException {
  Map jsonMap = new LinkedHashMap();
  JSONArray jsonArray = new JSONArray();
  if (xAttrs != null) {
    for (Entry<String, byte[]> e : xAttrs.entrySet()) {
      Map json = new LinkedHashMap();
      json.put(HttpFSFileSystem.XATTR_NAME_JSON, e.getKey());
      if (e.getValue() != null) {
        json.put(HttpFSFileSystem.XATTR_VALUE_JSON, 
            XAttrCodec.encodeValue(e.getValue(), encoding));
      }
      jsonArray.add(json);
    }
  }
  jsonMap.put(HttpFSFileSystem.XATTRS_JSON, jsonArray);
  return jsonMap;
}
项目:alvisnlp    文件:TextAnnotationDefinition.java   
@SuppressWarnings("unchecked")
@Override
protected void fillObject(JSONObject object, Element elt, int offset, CadixeExportContext ctx) {
    JSONArray position = new JSONArray();
    for (Element f : Iterators.loop(fragments.evaluateElements(ctx.evalCtx, elt))) {
        JSONArray text = new JSONArray();
        Annotation a = DownCastElement.toAnnotation(f);
        if (a == null)
            continue;
        text.add(a.getStart() + offset);
        text.add(a.getEnd() + offset);
        position.add(text);

    }
    object.put("text", position);
}
项目:EmojiChat    文件:Metrics.java   
@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;
}
项目:SayNoToMcLeaks    文件:Metrics.java   
@SuppressWarnings("unchecked")
@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;
      }
项目:burstcoin    文件:BlockImpl.java   
@Override
public JSONObject getJSONObject() {
    JSONObject json = new JSONObject();
    json.put("version", version);
    json.put("timestamp", timestamp);
    json.put("previousBlock", Convert.toUnsignedLong(previousBlockId));
    json.put("totalAmountNQT", totalAmountNQT);
    json.put("totalFeeNQT", totalFeeNQT);
    json.put("payloadLength", payloadLength);
    json.put("payloadHash", Convert.toHexString(payloadHash));
    json.put("generatorPublicKey", Convert.toHexString(generatorPublicKey));
    json.put("generationSignature", Convert.toHexString(generationSignature));
    if (version > 1) {
        json.put("previousBlockHash", Convert.toHexString(previousBlockHash));
    }
    json.put("blockSignature", Convert.toHexString(blockSignature));
    JSONArray transactionsData = new JSONArray();
    for (Transaction transaction : getTransactions()) {
        transactionsData.add(transaction.getJSONObject());
    }
    json.put("transactions", transactionsData);
    json.put("nonce", Convert.toUnsignedLong(nonce));
    json.put("blockATs", Convert.toHexString( blockATs ));
    return json;
}
项目:streamsx.jmxclients    文件:JobDetails.java   
@SuppressWarnings("unchecked")
private void resolveOperatorInputPortNames(JSONObject operator) {
    JSONArray inputPortArray = (JSONArray) operator.get("inputPorts");

    if (inputPortArray == null) {
        return;
    }

    String operatorName = getOperatorName(operator);
    Map<Integer, String> inputPortNames = operatorInputPortNames.get(operatorName);

    if (inputPortNames == null) {
        return;
    }

    for (int i = 0; i < inputPortArray.size(); i++) {
        JSONObject inputPort = (JSONObject) inputPortArray.get(i);
        int portIndex = getOperatorPortIndex(inputPort);
        String portName = inputPortNames.get(portIndex);

        if (portName != null) {
            inputPort.put("name", portName);
        }
    }
}
项目:burstcoin    文件:Users.java   
@Override
public void notify(Peer peer) {
    JSONObject response = new JSONObject();
    JSONArray removedActivePeers = new JSONArray();
    JSONObject removedActivePeer = new JSONObject();
    removedActivePeer.put("index", Users.getIndex(peer));
    removedActivePeers.add(removedActivePeer);
    response.put("removedActivePeers", removedActivePeers);
    JSONArray removedKnownPeers = new JSONArray();
    JSONObject removedKnownPeer = new JSONObject();
    removedKnownPeer.put("index", Users.getIndex(peer));
    removedKnownPeers.add(removedKnownPeer);
    response.put("removedKnownPeers", removedKnownPeers);
    JSONArray addedBlacklistedPeers = new JSONArray();
    JSONObject addedBlacklistedPeer = new JSONObject();
    addedBlacklistedPeer.put("index", Users.getIndex(peer));
    addedBlacklistedPeer.put("address", peer.getPeerAddress());
    addedBlacklistedPeer.put("announcedAddress", Convert.truncate(peer.getAnnouncedAddress(), "-", 25, true));
    if (peer.isWellKnown()) {
        addedBlacklistedPeer.put("wellKnown", true);
    }
    addedBlacklistedPeer.put("software", peer.getSoftware());
    addedBlacklistedPeers.add(addedBlacklistedPeer);
    response.put("addedBlacklistedPeers", addedBlacklistedPeers);
    Users.sendNewDataToAll(response);
}
项目:xbot_head    文件:JSON.java   
private static Object convertElementToField(Object element, Class fc, Field f, Registry<Class> r) {
    //System.out.println("JSON.convertElementToField: " + f.getName() + " " + fc.getName());
    Object value;
    if (element.getClass().equals(JSONObject.class)) {
        //System.out.println("JSON.convertElementToField: JSON Object " + ((JSONObject) element).toJSONString());
        value = convertJSONObjectToMessage((JSONObject) element, fc, r);
    }
    else if (element.getClass().equals(JSONArray.class)) {
        //System.out.println("JSON.convertElementToField: JSON Array " + ((JSONArray) element).toJSONString());
        if (Indication.asArray(f))
            value = convertJSONArrayToMessage((JSONArray) element, fc, r);
        else value = convertJSONArrayToArray((JSONArray) element, fc, r);
    }
    else {
        //System.out.println("JSON.convertElementToField: Primitive " + element);
        if (Indication.isBase64Encoded(f))
            value = convertBase64JSONStringToByteArray(element);
        else value = convertJSONPrimitiveToPrimitive(element, fc);
    }

    return value;        
}
项目:RNNavitiaSDK    文件:ArrayUtil.java   
public static Object[] toArray(JSONArray jsonArray) throws JSONException {
    Object[] array = new Object[jsonArray.size()];

    for (int i = 0; i < jsonArray.size(); i++) {
        Object value = jsonArray.get(i);

        if (value instanceof JSONObject) {
            value = MapUtil.toMap((JSONObject) value);
        }
        if (value instanceof JSONArray) {
            value = ArrayUtil.toArray((JSONArray) value);
        }

        array[i] = value;
    }

    return array;
}
项目:UltimateSpawn    文件:Metrics.java   
@SuppressWarnings("unchecked")
@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;
      }
项目:burstcoin    文件:Users.java   
@Override
public void notify(List<? extends Transaction> transactions) {
    JSONObject response = new JSONObject();
    JSONArray newTransactions = new JSONArray();
    for (Transaction transaction : transactions) {
        JSONObject newTransaction = new JSONObject();
        newTransaction.put("index", Users.getIndex(transaction));
        newTransaction.put("timestamp", transaction.getTimestamp());
        newTransaction.put("deadline", transaction.getDeadline());
        newTransaction.put("recipient", Convert.toUnsignedLong(transaction.getRecipientId()));
        newTransaction.put("amountNQT", transaction.getAmountNQT());
        newTransaction.put("feeNQT", transaction.getFeeNQT());
        newTransaction.put("sender", Convert.toUnsignedLong(transaction.getSenderId()));
        newTransaction.put("id", transaction.getStringId());
        newTransactions.add(newTransaction);
    }
    response.put("addedDoubleSpendingTransactions", newTransactions);
    Users.sendNewDataToAll(response);
}
项目:alfresco-repository    文件:CategoryPropertyDecorator.java   
/**
 * @see org.alfresco.repo.jscript.app.PropertyDecorator#decorate(org.alfresco.service.namespace.QName, org.alfresco.service.cmr.repository.NodeRef, java.io.Serializable)
 */
@SuppressWarnings("unchecked")
public JSONAware decorate(QName propertyName, NodeRef nodeRef, Serializable value)
{
    Collection<NodeRef> collection = (Collection<NodeRef>)value;
    JSONArray array = new JSONArray();

    for (NodeRef obj : collection)
    {
        try
        {
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("name", this.nodeService.getProperty(obj, ContentModel.PROP_NAME));
            jsonObj.put("path", this.getPath(obj));
            jsonObj.put("nodeRef", obj.toString());
            array.add(jsonObj);
        }
        catch (InvalidNodeRefException e)
        {
            logger.warn("Category with nodeRef " + obj.toString() + " does not exist.");
        }
    }

    return array;
}
项目:burstcoin    文件:User.java   
synchronized void processPendingResponses(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    JSONArray responses = new JSONArray();
    JSONStreamAware pendingResponse;
    while ((pendingResponse = pendingResponses.poll()) != null) {
        responses.add(pendingResponse);
    }
    if (responses.size() > 0) {
        JSONObject combinedResponse = new JSONObject();
        combinedResponse.put("responses", responses);
        if (asyncContext != null) {
            asyncContext.getResponse().setContentType("text/plain; charset=UTF-8");
            try (Writer writer = asyncContext.getResponse().getWriter()) {
                combinedResponse.writeJSONString(writer);
            }
            asyncContext.complete();
            asyncContext = req.startAsync();
            asyncContext.addListener(new UserAsyncListener());
            asyncContext.setTimeout(5000);
        } else {
            resp.setContentType("text/plain; charset=UTF-8");
            try (Writer writer = resp.getWriter()) {
                combinedResponse.writeJSONString(writer);
            }
        }
    } else {
        if (asyncContext != null) {
            asyncContext.getResponse().setContentType("text/plain; charset=UTF-8");
            try (Writer writer = asyncContext.getResponse().getWriter()) {
                JSON.emptyJSON.writeJSONString(writer);
            }
            asyncContext.complete();
        }
        asyncContext = req.startAsync();
        asyncContext.addListener(new UserAsyncListener());
        asyncContext.setTimeout(5000);
    }
}
项目:burstcoin    文件:GetBlocks.java   
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {

    int firstIndex = ParameterParser.getFirstIndex(req);
    int lastIndex = ParameterParser.getLastIndex(req);
    if (lastIndex < 0 || lastIndex - firstIndex > 99) {
        lastIndex = firstIndex + 99;
    }

    boolean includeTransactions = "true".equalsIgnoreCase(req.getParameter("includeTransactions"));

    JSONArray blocks = new JSONArray();
    try (DbIterator<? extends Block> iterator = Nxt.getBlockchain().getBlocks(firstIndex, lastIndex)) {
        while (iterator.hasNext()) {
            Block block = iterator.next();
            blocks.add(JSONData.block(block, includeTransactions));
        }
    }

    JSONObject response = new JSONObject();
    response.put("blocks", blocks);

    return response;
}
项目:burstcoin    文件:GetAllOpenAskOrders.java   
@Override
JSONStreamAware processRequest(HttpServletRequest req) {

    JSONObject response = new JSONObject();
    JSONArray ordersData = new JSONArray();

    int firstIndex = ParameterParser.getFirstIndex(req);
    int lastIndex = ParameterParser.getLastIndex(req);

    try (DbIterator<Order.Ask> askOrders = Order.Ask.getAll(firstIndex, lastIndex)) {
        while (askOrders.hasNext()) {
            ordersData.add(JSONData.askOrder(askOrders.next()));
        }
    }

    response.put("openOrders", ordersData);
    return response;
}
项目:Locked    文件:MerchantManager.java   
public static ArrayList<String> getAllNPCs() {
    ArrayList<String> a = new ArrayList<>();
    try {
        File file = plugin.getPath().getAbsoluteFile();
        JSONParser parser = new JSONParser();
        Object parsed = parser.parse(new FileReader(file.getPath()));
        JSONObject jsonObject = (JSONObject) parsed;
        JSONArray npcsArray = (JSONArray) jsonObject.get("npcs");
        for (Object npc : npcsArray) {
            a.add((String) ((JSONObject) npc).get("name"));

        }
    } catch (ParseException | IOException e) {
        e.printStackTrace();
    }
    return a;
}
项目:burstcoin    文件:GetBidOrders.java   
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException {

    long assetId = ParameterParser.getAsset(req).getId();
    int firstIndex = ParameterParser.getFirstIndex(req);
    int lastIndex = ParameterParser.getLastIndex(req);

    JSONArray orders = new JSONArray();
    try (DbIterator<Order.Bid> bidOrders = Order.Bid.getSortedOrders(assetId, firstIndex, lastIndex)) {
        while (bidOrders.hasNext()) {
            orders.add(JSONData.bidOrder(bidOrders.next()));
        }
    }
    JSONObject response = new JSONObject();
    response.put("bidOrders", orders);
    return response;
}
项目:Java-Data-Science-Cookbook    文件:JsonWriting.java   
public void writeJson(String outFileName){
    JSONObject obj = new JSONObject();
    obj.put("book", "Harry Potter and the Philosopher's Stone");
    obj.put("author", "J. K. Rowling");

    JSONArray list = new JSONArray();
    list.add("There are characters in this book that will remind us of all the people we have met. Everybody knows or knew a spoilt, overweight boy like Dudley or a bossy and interfering (yet kind-hearted) girl like Hermione");
    list.add("Hogwarts is a truly magical place, not only in the most obvious way but also in all the detail that the author has gone to describe it so vibrantly.");
    list.add("Parents need to know that this thrill-a-minute story, the first in the Harry Potter series, respects kids' intelligence and motivates them to tackle its greater length and complexity, play imaginative games, and try to solve its logic puzzles. ");

    obj.put("messages", list);

    try {

        FileWriter file = new FileWriter(outFileName);
        file.write(obj.toJSONString());
        file.flush();
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.print(obj);
}
项目:NameTagChanger    文件:Metrics.java   
@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;
}
项目:alfresco-remote-api    文件:SubscriptionServiceFollowsPost.java   
@SuppressWarnings("unchecked")
public JSONArray executeImpl(String userId, WebScriptRequest req, WebScriptResponse res) throws IOException,
        ParseException
{
    JSONArray jsonUsers = (JSONArray) JSONValue.parseWithException(req.getContent().getContent());

    JSONArray result = new JSONArray();

    for (Object o : jsonUsers)
    {
        String user = (o == null ? null : o.toString());
        if (user != null)
        {
            JSONObject item = new JSONObject();
            item.put(user, subscriptionService.follows(userId, user));
            result.add(item);
        }
    }

    return result;
}
项目:burstcoin    文件:GetAllOpenBidOrders.java   
@Override
JSONStreamAware processRequest(HttpServletRequest req) {

    JSONObject response = new JSONObject();
    JSONArray ordersData = new JSONArray();

    int firstIndex = ParameterParser.getFirstIndex(req);
    int lastIndex = ParameterParser.getLastIndex(req);

    try (DbIterator<Order.Bid> bidOrders = Order.Bid.getAll(firstIndex, lastIndex)) {
        while (bidOrders.hasNext()) {
            ordersData.add(JSONData.bidOrder(bidOrders.next()));
        }
    }

    response.put("openOrders", ordersData);
    return response;
}
项目:sonar-coverage-evolution    文件:DefaultSonarClient.java   
protected static <G extends Serializable> Optional<String> extractMeasure(JsonObject apiResult, Metric<G> metric) {
  JsonObject component = apiResult.getMap("component");
  if (component == null) {
    return Optional.empty();
  }
  JsonArray measures = component.getCollection("measures");
  if (measures == null) {
    return Optional.empty();
  }
  return measures.stream()
      .map(o -> (JsonObject) o)
      .filter(o ->
        metric.getKey().equals(o.getString("metric"))
      )
      .map(o ->
        o.getString("value")
      )
      .findFirst();

}
项目:shipkit    文件:FindOpenPullRequest.java   
public PullRequest findOpenPullRequest(String upstreamRepositoryName, String versionBranchRegex, GitHubApi gitHubApi) throws IOException {
    String response = gitHubApi.get("/repos/" + upstreamRepositoryName + "/pulls?state=open");

    JsonArray pullRequests = Jsoner.deserialize(response, new JsonArray());

    for (Object pullRequest : pullRequests) {
        PullRequest openPullRequest = PullRequestUtils.toPullRequest((JsonObject) pullRequest);
        if (openPullRequest != null && openPullRequest.getRef().matches(versionBranchRegex)) {
            LOG.lifecycle("  Found an open pull request with version upgrade on branch {}", openPullRequest.getRef());
            return openPullRequest;
        }
    }

    LOG.lifecycle("  New pull request will be opened because we didn't find an existing PR to reuse.");

    return null;
}