當前位置: 首頁>>代碼示例>>Java>>正文


Java JSONParser類代碼示例

本文整理匯總了Java中org.json.simple.parser.JSONParser的典型用法代碼示例。如果您正苦於以下問題:Java JSONParser類的具體用法?Java JSONParser怎麽用?Java JSONParser使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


JSONParser類屬於org.json.simple.parser包,在下文中一共展示了JSONParser類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: handleWeatherMessage

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
/**
 * handleWeatherMessage takes received telemetry message and processes it to be printed to command line.
 * @param msg Telemetry message received through hono server.
 */
private void handleWeatherMessage(final Message msg) {
    final Section body = msg.getBody();
    //Ensures that message is Data (type of AMQP messaging). Otherwise exits method.
    if (!(body instanceof Data))
        return;
    //Gets deviceID.
    final String deviceID = MessageHelper.getDeviceId(msg);
    //Creates JSON parser to read input telemetry weather data. Prints data to console output.
    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(((Data) msg.getBody()).getValue().toString());
        JSONObject payload = (JSONObject) obj;
        System.out.println(new StringBuilder("Device: ").append(deviceID).append("; Location: ").
                append(payload.get("location")).append("; Temperature:").append(payload.get("temperature")));
    } catch (ParseException e) {
        System.out.println("Data was not sent in a readable way. Check telemetry input.");
        e.printStackTrace();
    }
}
 
開發者ID:rhiot,項目名稱:hono-weather-demo,代碼行數:24,代碼來源:WeatherDataConsumer.java

示例2: mergeFiles

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
/**
 * merge source file into target
 *
 * @param target
 * @param source
 */
public void mergeFiles(File target, File source) throws Throwable {
    String targetReport = FileUtils.readFileToString(target);
    String sourceReport = FileUtils.readFileToString(source);

    JSONParser jp = new JSONParser();

    try {
        JSONArray parsedTargetJSON = (JSONArray) jp.parse(targetReport);
        JSONArray parsedSourceJSON = (JSONArray) jp.parse(sourceReport);
        // Merge two JSON reports
        parsedTargetJSON.addAll(parsedSourceJSON);
        // this is a new writer that adds JSON indentation.
        Writer writer = new JSONWriter();
        // convert our parsedJSON to a pretty form
        parsedTargetJSON.writeJSONString(writer);
        // and save the pretty version to disk
        FileUtils.writeStringToFile(target, writer.toString());
    } catch (ParseException pe) {
        pe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
開發者ID:usman-h,項目名稱:Habanero,代碼行數:30,代碼來源:JSONReportMerger.java

示例3: getDisplayName

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
/**
 * Tries to fetch the current display name for the user
 *
 * @param id the id of the user to check
 * @return the current display name of that user
 * @throws IOException           if something goes wrong
 * @throws VoxelGameLibException if the user has no display name
 */
@Nonnull
public static String getDisplayName(@Nonnull UUID id) throws IOException, VoxelGameLibException {
    URL url = new URL(NAME_HISTORY_URL.replace("%1", id.toString().replace("-", "")));
    System.out.println(url.toString());
    Scanner scanner = new Scanner(new BufferedReader(new InputStreamReader(url.openStream())));
    if (scanner.hasNext()) {
        String json = scanner.nextLine();
        try {
            JSONArray jsonArray = (JSONArray) new JSONParser().parse(json);
            if (json.length() > 0) {
                return (String) ((JSONObject) jsonArray.get(0)).get("name");
            }
        } catch (ParseException ignore) {
        }
    }

    throw new VoxelGameLibException("User has no name! " + id);
}
 
開發者ID:VoxelGamesLib,項目名稱:VoxelGamesLibv2,代碼行數:27,代碼來源:MojangUtil.java

示例4: sizeJSON

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
public static int sizeJSON(String s) {
	Object obj;
	try {
		obj = new JSONParser().parse(new StringReader(s));
	} catch (IOException | ParseException e) {
		return 0;
	}

	if (obj instanceof JSONObject) {
        JSONObject jo = (JSONObject) obj;
        return jo.entrySet().size();
	}

	if (obj instanceof JSONArray) {
		JSONArray ja = (JSONArray) obj;
        return ja.size();
	}

	return 0;
}
 
開發者ID:Nexenta,項目名稱:edgex-java-connector,代碼行數:21,代碼來源:JSONUtil.java

示例5: fromJSON

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
public static SessionToken fromJSON(String json) {
    JSONParser parser = new JSONParser();

    try {
        JSONObject obj = (JSONObject) parser.parse(json);

        if(!obj.containsKey("TOKENTYPE") || !obj.get("TOKENTYPE").equals(TOKEN_TYPE)) {
            return null;
        }

        if(!obj.containsKey("serverID") || !obj.containsKey("uuid") ||
                !obj.containsKey("timestamp") || !obj.containsKey("expires"))
            throw new IllegalArgumentException("JSON is invalid: missing keys!");

        return new SessionToken((String) obj.get("serverID"), (String) obj.get("uuid"), (long) obj.get("timestamp"), (long) obj.get("expires"));
    } catch (ParseException e) {
        throw new IllegalArgumentException(e);
    }
}
 
開發者ID:jython234,項目名稱:nectar-server,代碼行數:20,代碼來源:SessionToken.java

示例6: getController

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
private String getController(String topologyFile) throws Exception {
    ClassLoader classLoader = getClass().getClassLoader();
    URL resource = classLoader.getResource(topologyFile);
    if (resource == null) {
        throw new IllegalArgumentException(String.format("No such topology json file: %s", topologyFile));
    }

    File file = new File(resource.getFile());
    String json = new String(Files.readAllBytes(file.toPath()));
    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(json);
    JSONArray controllers = (JSONArray) jsonObject.get("controllers");

    JSONObject controller = (JSONObject) controllers.get(0);
    return  (String) controller.get("host");
}
 
開發者ID:telstra,項目名稱:open-kilda,代碼行數:17,代碼來源:FlowFFRTest.java

示例7: doExecuteJSONRequest

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
public static JSONObject doExecuteJSONRequest(RemoteConnectorRequest request, RemoteConnectorService service) throws ParseException, IOException, AuthenticationException
{
    // Set as JSON
    request.setContentType(MimetypeMap.MIMETYPE_JSON);
    
    // Perform the request
    RemoteConnectorResponse response = service.executeRequest(request);
    
    // Parse this as JSON
    JSONParser parser = new JSONParser();
    String jsonText = response.getResponseBodyAsString();
    Object json = parser.parse(jsonText);
    
    // Check it's the right type and return
    if (json instanceof JSONObject)
    {
        return (JSONObject)json;
    }
    else
    {
        throw new ParseException(0, json);
    }
}
 
開發者ID:Alfresco,項目名稱:alfresco-repository,代碼行數:24,代碼來源:RemoteConnectorServiceImpl.java

示例8: getInstance

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
/**
 *
 * @return @throws FileNotFoundException
 * @throws IOException
 * @throws ParseException
 */
public static DBProperties getInstance() throws FileNotFoundException, IOException, ParseException {
    DBProperties properties = new DBProperties();
    JSONParser jsonParser = new JSONParser();
    Object file = jsonParser.parse(new FileReader(new File(Context.getDbConfig())));

    JSONObject jsonObject = (JSONObject) file;

    properties.setDbhost((String) jsonObject.get("db_host"));
    properties.setDbname((String) jsonObject.get("db_name"));
    properties.setDbport((String) jsonObject.get("db_port"));
    properties.setDbuser((String) jsonObject.get("db_user"));
    properties.setPassword((String) jsonObject.get("password"));
    properties.setUrl((String) jsonObject.get("access_url"));
    properties.setDriver((String) jsonObject.get("jdbc_driver_class"));

    LOGGER.debug("DB Connection: " + properties.getConnectionUrl());
    return properties;
}
 
開發者ID:benj-c,項目名稱:java-gps-tracking-server,代碼行數:25,代碼來源:DBPropertiesResource.java

示例9: refreshAccessToken

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
/**
 * Refreshes the Access Token of the currently used account
 */
public void refreshAccessToken() {
    this.updateHTTPParameter();
    JodelHTTPResponse requestResponse = this.httpAction.getNewAccessToken();
    if (requestResponse.responseCode == 200) {
        String responseMessage = requestResponse.responseMessage;
        JSONParser parser = new JSONParser();
        try {
            JSONObject responseJson = (JSONObject) parser.parse(responseMessage);
            this.accessToken = responseJson.get("access_token").toString();
            this.expirationDate = responseJson.get("expiration_date").toString();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
 
開發者ID:fr31b3u73r,項目名稱:JodelAPI,代碼行數:20,代碼來源:JodelAccount.java

示例10: getJodelShareLink

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
/**
 * Get share url
 * @param postID ID of the post to share
 * @return The requestResponse of type JodelRequestResponse
 */
public JodelRequestResponse getJodelShareLink(String postID) {
    JodelRequestResponse requestResponse = new JodelRequestResponse();
    this.updateHTTPParameter();
    JodelHTTPResponse getShareLink = this.httpAction.getJodelShareURL(postID);
    requestResponse.httpResponseCode = getShareLink.responseCode;
    if (getShareLink.responseCode == 200) {
        String responseJodelsMessage = getShareLink.responseMessage;
        requestResponse.rawResponseMessage = responseJodelsMessage;
        JSONParser parser = new JSONParser();
        try {
            JSONObject responseJson = (JSONObject) parser.parse(responseJodelsMessage);
            String url = (String) responseJson.get("url");
            requestResponse.responseValues.put("shareLink", url);
        } catch (Exception e) {
            requestResponse.rawErrorMessage = e.getMessage();
            e.printStackTrace();
            requestResponse.error = true;
            requestResponse.errorMessage = "Could not parse response JSON!";
        }
    } else {
        requestResponse.error = true;
    }
    return requestResponse;
}
 
開發者ID:fr31b3u73r,項目名稱:JodelAPI,代碼行數:30,代碼來源:JodelAccount.java

示例11: getKarma

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
/**
 * Gets your karma
 * @return The requestResponse of type JodelRequestResponse
 */
public JodelRequestResponse getKarma() {
    JodelRequestResponse requestResponse = new JodelRequestResponse();
    this.updateHTTPParameter();
    JodelHTTPResponse karmaResponse = this.httpAction.getKarma();
    requestResponse.httpResponseCode = karmaResponse.responseCode;
    if (requestResponse.httpResponseCode == 200) {
        String responseKarma = karmaResponse.responseMessage;
        requestResponse.rawResponseMessage = responseKarma;
        JSONParser parserCaptcha = new JSONParser();
        try {
            JSONObject responseCaptchaJson = (JSONObject) parserCaptcha.parse(responseKarma);
            String karma = responseCaptchaJson.get("karma").toString();
            requestResponse.responseValues.put("karma", karma);

        } catch (ParseException e) {
            requestResponse.rawErrorMessage = e.getMessage();
            e.printStackTrace();
            requestResponse.error = true;
            requestResponse.errorMessage = "Could not parse response JSON!";
        }
    } else {
        requestResponse.error = true;
    }
    return requestResponse;
}
 
開發者ID:fr31b3u73r,項目名稱:JodelAPI,代碼行數:30,代碼來源:JodelAccount.java

示例12: setParams

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
/**
 * Builds URL params from input JSON string
 *
 * @param builder
 * @param jsonStr
 * @return
 * @throws ParseException
 */
public URIBuilder setParams(URIBuilder builder, String jsonStr) throws ParseException {

    if (jsonStr != null && !"".equals(jsonStr)) {
        try {
            JSONParser parser = new JSONParser();
            JSONObject json = (JSONObject) parser.parse(jsonStr);
            json.keySet().forEach((Key) -> {
                builder.setParameter(Key.toString(), (String) json.get(Key));
            });
        } catch (Exception ex) {
            DLogger.LogE(ex.getMessage());
            LOG.log(Level.SEVERE, ex.getMessage(), ex);
        }

    }

    return builder;
}
 
開發者ID:CognizantQAHub,項目名稱:Cognizant-Intelligent-Test-Scripter,代碼行數:27,代碼來源:AbstractHttpClient.java

示例13: getJSON

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
@Override
public JSONObject getJSON() {
    try {
        JSONObject nodeJSON = new JSONObject();
        JSONParser parser = new JSONParser();

        nodeJSON.put("id", id);
        nodeJSON.put("lat", lat);
        nodeJSON.put("lon", lon);
        nodeJSON.put("tags", parser.parse(gson.toJson(tags)));
        return nodeJSON;
    }
    catch (ParseException e){
        System.err.println("Error caught in parsing gson object");
        return null;
    }
}
 
開發者ID:OliMac1,項目名稱:durafficpark,代碼行數:18,代碼來源:OSMNode.java

示例14: createRemascConfig

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
public RemascConfig createRemascConfig(String config) {
    RemascConfig remascConfig;

    try (InputStream is = RemascConfigFactory.class.getClassLoader()
            .getResourceAsStream(this.configPath); InputStreamReader fileReader = new InputStreamReader(is)){

        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(fileReader);
        JSONObject jsonConfig = (JSONObject) jsonObject.get(config);
        String remascString = jsonConfig.toString();
        remascConfig = mapper.readValue(remascString, RemascConfig.class);
    } catch (Exception ex) {
        logger.error("Error reading REMASC configuration[{}]: {}", config, ex);
        throw new RemascException("Error reading REMASC configuration[" + config +"]: ", ex);
    }

    return remascConfig;
}
 
開發者ID:rsksmart,項目名稱:rskj,代碼行數:19,代碼來源:RemascConfigFactory.java

示例15: load

import org.json.simple.parser.JSONParser; //導入依賴的package包/類
public ConcurrentMap<String, AccountData> load() {
    ConcurrentHashMap<String, AccountData> accounts = new ConcurrentHashMap<>();
    if(Files.exists(filePath)) {
        try (FileReader fileReader = new FileReader(this.filePath.toString())){
            JSONParser parser = new JSONParser();
            Object json = parser.parse(fileReader);
            JSONObject jsonObject = (JSONObject) json;
            JSONArray jsonAccounts = (JSONArray) jsonObject.get("accounts");

            for(Object obj : jsonAccounts) {
                JSONObject jobj = (JSONObject) obj;
                String acc  = (String) jobj.get("account");
                String add  = (String) jobj.get("address");
                accounts.put((String) jobj.get("ip"), new AccountData(stringHexToByteArray(add), stringHexToByteArray(acc)));
            }
        } catch (ParseException | IOException e) {
            logger.error("Error reading accounts file", e);
        }
    }
    return accounts;
}
 
開發者ID:rsksmart,項目名稱:rskj,代碼行數:22,代碼來源:AccountFileLoader.java


注:本文中的org.json.simple.parser.JSONParser類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。