当前位置: 首页>>代码示例>>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;未经允许,请勿转载。