Java net.minidev.json.JSONObject 代码实例

・20 分钟阅读

以下是展示如何使用net.minidev.json.JSONObject的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public String createJsonClassifiedTweetIDString(ClassifiedTweet tweet) {
        JSONObject obj = new JSONObject();
        obj.put("id", tweet.getTweetID());
        obj.put("crisis_name", tweet.getCrisisName());
        if (tweet.getNominalLabels() != null) {
                List<NominalLabel> nbList = tweet.getNominalLabels();
                for (int i = 0; i < nbList.size(); i++) {
                        NominalLabel nb = nbList.get(i);
                        obj.put("attribute_name_" + i, nb.attribute_name);
                        obj.put("attribute_code_" + i, nb.attribute_code);
                        obj.put("label_name_" + i, nb.label_name);
                        obj.put("label_description_" + i, nb.label_description);
                        obj.put("label_code_" + i, nb.label_code);
                        obj.put("confidence_" + i, nb.confidence);
                        obj.put("humanLabeled_" + i, nb.from_human);
                }
        }
        return obj.toJSONString();
}
 

实例 2


public JSONObject getTagCountSumForAllAttributesFromTime(String crisisCode, Long granularity, Long startTime) {
        List<String> attributesList = tagDataEJB.getAttributesForCrisis(crisisCode);
        List<TagData> tagDataList = new ArrayList<TagData>();
        JSONObject jsonList = new JSONObject();
        jsonList.put("crisisCode", crisisCode);
        jsonList.put("granularity", granularity);
        jsonList.put("startTime", startTime);
        if (attributesList != null) {
                jsonList.put("attributesList", attributesList);
                Map<String, Object> dataSet = new HashMap<String, Object>();
                for (String attribute: attributesList) {
                        tagDataList.addAll(tagDataEJB.getDataAfterTimestampGranularity(crisisCode, attribute, null, startTime, granularity));
                        // Now the real work - count and send response
                        JSONObject json = new JsonResponse().getNewJsonResponseObject(crisisCode, attribute, granularity, startTime, null);
                        if (tagDataList != null) {
                                Map<String, Integer> tagCountMap = new TreeMap<String, Integer>();
                                for (TagData t: tagDataList) {
                                        if (tagCountMap.containsKey(t.getLabelCode())) {
                                                tagCountMap.put(t.getLabelCode(), tagCountMap.get(t.getLabelCode()) + t.getCount());
                                        } else {
                                                tagCountMap.put(t.getLabelCode(), t.getCount());
                                        }
                                }
                                try {
                                        json.put("data", tagCountMap);
                                        dataSet.put(attribute, json);
                                } catch (Exception e) {
                                        json = JsonResponse.addError(json);
                                        logger.error("Error in serializing fetched tag count data", e);
                                }
                        }
                }
                jsonList.put("attribute_data", dataSet);
        }
        return jsonList;
}
 

实例 3


public void testF1() {
        String test = "51e88";
        JSONObject o = new JSONObject();
        o.put("a", test);
        String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS);
        assertEquals("{a:"51e88"}", comp);
        o = JSONValue.parse(comp, JSONObject.class);
        assertEquals(o.get("a"), test);
}
 

实例 4


public void testF2() {
        String test = "51e+88";
        JSONObject o = new JSONObject();
        o.put("a", test);
        String comp = JSONValue.toJSONString(o, JSONStyle.MAX_COMPRESS);
        assertEquals("{a:"51e+88"}", comp);
        o = JSONValue.parse(comp, JSONObject.class);
        assertEquals(o.get("a"), test);
}
 

实例 5


private String[] getMinecraftArguments(MinecraftInstance mc, File assetsDir,
                                      ISession session, ILaunchSettings settings,
                                      MCDownloadVersion version) {
    // TODO tooo lazy to finish options
    String args = version.getMinecraftArgs();
    StringSubstitutor subst = new StringSubstitutor("${%s}");
    subst.setVariable("auth_session", session.getSessionID());
    subst.setVariable("auth_access_token", session.getSessionID());
    subst.setVariable("auth_player_name", session.getUsername());
    subst.setVariable("auth_uuid", session.getUUID());
    subst.setVariable("version_name", version.getId());
    subst.setVariable("game_directory", mc.getLocation().getAbsolutePath());
    subst.setVariable("game_assets", assetsDir
            .getAbsolutePath());
    subst.setVariable("assets_root", assetsDir
            .getAbsolutePath());
    subst.setVariable("assets_index_name", version.getAssetsIndexName());
    subst.setVariable("user_type", session.getType().toString()
            .toLowerCase());
    if (session.getProperties() != null
            && !session.getProperties().isEmpty()) {
        JSONObject propertiesObj = new JSONObject();
        List<Prop> properties = session.getProperties();
        for (Prop p : properties) {
            propertiesObj.put(p.name, p.value);
        }
        subst.setVariable("user_properties",
                propertiesObj.toJSONString(JSONStyle.NO_COMPRESS));
    } else
        subst.setVariable("user_properties", "{}");
    args = subst.substitute(args);
    return args.split(" ");
}
 

实例 6


@Override
public JSONObject toJSON() {
    JSONObject obj = new JSONObject();
    obj.put("agent", agentObj);
    obj.put("clientToken", token);
    obj.put("username", user);
    obj.put("password", pass);
    return obj;
}
 

实例 7


/**
 * Returns the result of the search operation
 *
 * @param term        - the string being searched for
 * @param ontologyIds - the ontologies the search is being restricted to
 * @param @nullable   subtree - a subtree, if any to be searched under (optional)
 * @return - Map from the id of the ontology to the list of terms found under it.
 */
public Map<String, List<OntologyTerm>> getSearchResults(String term, String ontologyIds, String subtree, boolean exactMatch) {
    // map from ontology id to the list of terms found for that id.
    Map<String, List<OntologyTerm>> result = new HashMap<String, List<OntologyTerm>>();
    String content = querySearchEndpoint(term, ontologyIds, subtree, exactMatch);
    JSONObject obj = (JSONObject) JSONValue.parse(content);
    JSONArray results = (JSONArray) obj.get("collection");
    if (results == null)
        return result;
    for (Object result1 : results) {
        JSONObject resultItem = (JSONObject) result1;
        String ontologyId = extractOntologyId(resultItem);
        if (!result.containsKey(ontologyId)) {
            result.put(ontologyId, new ArrayList<OntologyTerm>());
        }
        OntologyTerm ontologyTerm = createOntologyTerm(resultItem);
        result.get(ontologyId).add(ontologyTerm);
    }
    return result;
}
 

实例 8


public void testString() throws Exception {
        for (String nonLatinText : nonLatinTexts) {
                String s = "{"key":"" + nonLatinText + ""}";
                JSONObject obj = (JSONObject) JSONValue.parse(s);
                String v = (String) obj.get("key"); // result is incorrect
                assertEquals(v, nonLatinText);
        }
}
 

实例 9


public void testReader() throws Exception {
        for (String nonLatinText : nonLatinTexts) {
                String s = "{"key":"" + nonLatinText + ""}";
                StringReader reader = new StringReader(s);
                JSONObject obj = (JSONObject) JSONValue.parse(reader);
                String v = (String) obj.get("key"); // result is incorrect
                assertEquals(v, nonLatinText);
        }
}
 

实例 10


public Library(JSONObject json) {
    name = json.get("name").toString();
    if (json.containsKey("natives")) {
        JSONObject nativesObj = (JSONObject) json.get("natives");
        for (String nativeKey : nativesObj.keySet()) {
            String key = nativeKey;
            String value = nativesObj.get(nativeKey).toString();
            natives.put(key, value);
        }
    }
    if (json.containsKey("rules")) {
        JSONArray rulz = (JSONArray) json.get("rules");
        for (int i = 0; i < rulz.size(); ++i) {
            rules.add(new Rule((JSONObject) rulz.get(i)));
        }
    }
    if (json.containsKey("extract")) {
        extractRules = new LibraryExtractRules((JSONObject) json.get("extract"));
    }
    if (json.containsKey("url")) {
        url = json.get("url").toString();
    }
}
 

实例 11


MCDownloadVersion(JSONObject json) {
    this.json = json;
    id = json.get("id").toString();
    if(json.containsKey("jar")) {
        jarVersion = json.get("jar").toString();
    } else {
        jarVersion = id;
    }
    time = json.get("time").toString();
    releaseTime = json.get("releaseTime").toString();
    type = json.get("type").toString();
    if (json.containsKey("processArguments"))
        processArgs = json.get("processArguments").toString();
    minecraftArgs = json.get("minecraftArguments").toString();
    minimumLauncherVersion = Integer.parseInt(json.get("minimumLauncherVersion").toString());
    mainClass = json.get("mainClass").toString();
    if (json.containsKey("assets"))
        assets = json.get("assets").toString();
    else
        assets = DEFAULT_ASSETS_INDEX;
    if (json.containsKey("rules")) {
        JSONArray rulesArray = (JSONArray) json.get("rules");
        for (Object o : rulesArray) {
            JSONObject jsonRule = (JSONObject) o;
            rules.add(new Rule(jsonRule));
        }
    }
    if (json.containsKey("libraries")) {
        JSONArray libs = (JSONArray) json.get("libraries");
        for (int i = 0; i < libs.size(); ++i) {
            libraries.add(new Library((JSONObject) libs.get(i)));
        }
    }
    if (json.containsKey("incompatibilityReason"))
        incompatibilityReason = json.get("incompatibilityReason").toString();
    if (json.containsKey("inheritsFrom")) {
        inheritsFrom = json.get("inheritsFrom").toString();
        needsInheritance = true;
    } else
        needsInheritance = false;
}
 

实例 12


@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/genCSV")
public Response generateCSVFromLastestJSON(@QueryParam("collectionCode") String collectionCode,
                                @QueryParam("exportLimit") int exportLimit) throws UnknownHostException {
        logger.info("Received request for collection: " + collectionCode);
        JsonDeserializer jsonD = new JsonDeserializer();
    String fileName = jsonD.generateJSON2CSV_100K_BasedOnTweetCount(collectionCode, exportLimit);
    fileName = PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.PERSISTER_DOWNLOAD_URL) + collectionCode+"/"+fileName;
    logger.info("Done processing request for collection: " + collectionCode + ", returning created file: " + fileName);
    //return Response.ok(fileName).build();
    JSONObject obj = new JSONObject();
    obj.putAll(ResultStatus.getUIWrapper(collectionCode, null, fileName, true));
    logger.info("Returning JSON object: " + ResultStatus.getUIWrapper(collectionCode, null, fileName, true));
    return Response.ok(obj.toJSONString()).build();
}
 

实例 13


@GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("/genTweetIds")
  public Response generateTweetsIDSCSVFromAllJSON(@QueryParam("collectionCode") String collectionCode,
                @DefaultValue("true") @QueryParam("downloadLimited") Boolean downloadLimited) throws UnknownHostException {
      logger.info("Received request for collection: " + collectionCode);
        JsonDeserializer jsonD = new JsonDeserializer();
        Map<String, Object> result = jsonD.generateJson2TweetIdsCSV(collectionCode, downloadLimited);
      String fileName = PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.PERSISTER_DOWNLOAD_URL) + collectionCode+"/" + (String) result.get("fileName");
      logger.info("Done processing request for collection: " + collectionCode + ", returning created file: " + fileName);
      JSONObject obj = new JSONObject();
if ((Integer) result.get("count") < Integer.parseInt(PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_TWEETID_VOLUME_LIMIT)) ) {
        obj.putAll(ResultStatus.getUIWrapper(collectionCode, null, fileName, true));
        logger.info("Returning JSON object: " + ResultStatus.getUIWrapper(collectionCode, null, fileName, true));
        return Response.ok(obj.toJSONString()).build();
} else {
        obj.putAll(ResultStatus.getUIWrapper(collectionCode,PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_PREFIX) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_TWEETID_VOLUME_LIMIT) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_SUFFIX), fileName, true));
        logger.info("Returning JSON object: " + ResultStatus.getUIWrapper(collectionCode,  PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_PREFIX) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.DEFAULT_TWEETID_VOLUME_LIMIT) + PersisterConfigurator.getInstance().getProperty(PersisterConfigurationProperty.TWEET_DOWNLOAD_LIMIT_MSG_SUFFIX), fileName, true));
        return Response.ok(obj.toJSONString()).build();
}
  }
 

实例 14


protected void queuePersistedMessages(final ServerSession serverSession,
        List<Map<String, Object>> messages, final String topic) {
    for (Map<String, Object> notification : messages) {
        final JSONObject jsonPropMap = new JSONObject();
        jsonPropMap.putAll(notification);
        LOGGER.debug("Sending the following property map "{}": ", jsonPropMap.toJSONString());
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                int maxAttempts = 10;
                int attempts = 0;
                while (!serverSession.isConnected() && attempts < maxAttempts) {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                    }
                    attempts++;
                    LOGGER.trace("Attempt {} of {} to send notifications back to client.",
                            attempts, maxAttempts);
                }
                LOGGER.trace("Sending notifications back to client.");
                serverSession
                        .deliver(controllerServerSession, topic, jsonPropMap.toJSONString(),
                                null);
            }
        });
    }
}
 

实例 15


public String doLayout(ILoggingEvent loggingEvent) {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("@version", version);
    jsonObject.put("@timestamp", simpleDateFormat.format(new Date(loggingEvent.getTimeStamp())));
    jsonObject.put("logger_full", loggingEvent.getLoggerName());
    jsonObject.put("level", loggingEvent.getLevel().toString());
    jsonObject.put("message", loggingEvent.getFormattedMessage());
    jsonObject.put("mdc", loggingEvent.getMDCPropertyMap());
    jsonObject.put("thread", loggingEvent.getThreadName());
    jsonObject.put("host", host);
    handleLoggerSimpleName(loggingEvent, jsonObject);
    handleThrowableInformation(loggingEvent, jsonObject);
    jsonObject.putAll(getUserFieldsMap());
    return jsonObject.toString();
}
 
讨论
淘淘あ西西 profile image