当前位置: 首页>>代码示例>>Java>>正文


Java JSONParser.parse方法代码示例

本文整理汇总了Java中org.json.simple.parser.JSONParser.parse方法的典型用法代码示例。如果您正苦于以下问题:Java JSONParser.parse方法的具体用法?Java JSONParser.parse怎么用?Java JSONParser.parse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.json.simple.parser.JSONParser的用法示例。


在下文中一共展示了JSONParser.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getAP

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
public String getAP(String json) throws ParseException {
    long apAmount = -1;
    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) == 30103) {
                criteriaNumber = i;
            }
        }

        if (criteriaNumber != -1) {
            apAmount = (long) ((JSONArray)achivements.get("criteriaQuantity")).get(criteriaNumber);
        }
    }
    String result = null;
    if (apAmount != -1) {
        result = format(apAmount);
    }
    return result;

}
 
开发者ID:greatman,项目名称:legendarybot,代码行数:26,代码来源:IlvlCommand.java

示例2: 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

示例3: 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

示例4: getAclEntries

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
/**
 * Given the JSON output from the GETACLSTATUS call, return the
 * 'entries' value as a List<String>.
 * @param statusJson JSON from GETACLSTATUS
 * @return A List of Strings which are the elements of the ACL entries
 * @throws Exception
 */
private List<String> getAclEntries ( String statusJson ) throws Exception {
  List<String> entries = new ArrayList<String>();
  JSONParser parser = new JSONParser();
  JSONObject jsonObject = (JSONObject) parser.parse(statusJson);
  JSONObject details = (JSONObject) jsonObject.get("AclStatus");
  JSONArray jsonEntries = (JSONArray) details.get("entries");
  if ( jsonEntries != null ) {
    for (Object e : jsonEntries) {
      entries.add(e.toString());
    }
  }
  return entries;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:21,代码来源:TestHttpFSServer.java

示例5: testHandleAttributeRemoved

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
/**
 * Test of {@code handleAttributeRemoved} method.
 */
@Test
public void testHandleAttributeRemoved() throws ParseException {
    TransportImplementation transport = new DummyTransportImplementation();
    DOM dom = new DOM(new TransportHelper(transport), null);
    final Node root = dom.getDocument();
    final String ATTR_NAME = "class"; // NOI18N
    final int[] eventsFired = new int[1];
    DOM.Listener listener = new DOMAdapter() {
        @Override
        public void attributeRemoved(Node node, String attrName) {
            eventsFired[0]++;
            assertEquals(ATTR_NAME, attrName);
            assertEquals(root, node);
            Node.Attribute attr = node.getAttribute(attrName);
            assertNull(attr);
        }
    };
    dom.addListener(listener);
    JSONParser parser = new JSONParser();

    // Modification of a known node
    Object json = parser.parse("{\"nodeId\":" + ROOT_NODE_ID + ",\"name\":\"" + ATTR_NAME + "\"}"); // NOI18N
    dom.handleAttributeRemoved((JSONObject)json);
    assertEquals(1, eventsFired[0]);

    // Modification of an unknown node
    json = parser.parse("{\"nodeId\":" + (ROOT_NODE_ID+1) + ",\"name\":\"someName\"}"); // NOI18N
    dom.handleAttributeRemoved((JSONObject)json);
    assertEquals(1, eventsFired[0]);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:34,代码来源:DOMTest.java

示例6: convertToItem

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
private static <T> T convertToItem(String item, Class<T> clazz) throws ParseException {
    if (clazz == JSONObject.class || clazz == Map.class) {
        // JSON部分のみを取り出す。
        int jsonStart = item.indexOf("{");
        String json = "{}";
        if (-1 < jsonStart) {
            json = item.substring(jsonStart);
            JSONParser parser = new JSONParser();
            return (T) parser.parse(json);
        }
    }
    return (T) item;
}
 
开发者ID:personium,项目名称:personium-core,代码行数:15,代码来源:BatchResponseExtractor.java

示例7: fromJSON

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
public static ManagementSessionToken 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("clientIP") ||
                !obj.containsKey("timestamp") || !obj.containsKey("expires"))
            throw new IllegalArgumentException("JSON is invalid: missing keys!");

        return new ManagementSessionToken((String) obj.get("serverID"), (String) obj.get("clientIP"), (long) obj.get("timestamp"), (long) obj.get("expires"));
    } catch (ParseException e) {
        throw new IllegalArgumentException(e);
    }
}
 
开发者ID:jython234,项目名称:nectar-server,代码行数:20,代码来源:ManagementSessionToken.java

示例8: parse

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
/**
 * parse into java object from input source.
 * @param in
 * @return instance of : JSONObject,JSONArray,String,Boolean,Long,Double or null
 */
public static Object parse(Reader in){
	try{
		JSONParser parser=new JSONParser();
		return parser.parse(in);
	}
	catch(Exception e){
		return null;
	}
}
 
开发者ID:BiglySoftware,项目名称:BiglyBT,代码行数:15,代码来源:JSONValue.java

示例9: searchAPI

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
/**
 * Perform a query on a given UCL API connection and return an array equipment.
 * @param conn UCLApiConnection
 * @param endpoint the API path
 * @param params hashtable of query parameters
 * @return Array of Equipment
 */
public static Equipment[] searchAPI(UCLApiConnection conn, String endpoint, Hashtable<String, String> params) {
    String response = conn.queryAPI(endpoint, params);

    try {
        JSONParser p = new JSONParser();
        JSONObject responseObject = (JSONObject)p.parse(response);

        JSONArray equipment = (JSONArray)responseObject.get("equipment");
        int nEquipment = equipment.size();
        Equipment[] retval = new Equipment[nEquipment];

        for (int i = 0; i < nEquipment; i++) {
            JSONObject jeq = (JSONObject)equipment.get(i);

            retval[i] = new Equipment(jeq);

        }

        return retval;

    } catch (Exception e){
        System.err.println(e.toString());
        if (uclapi.UCLApiConnection.ExitOnException) {
            System.exit(5);
        }
    }
    return new Equipment[0];
}
 
开发者ID:owainkenwayucl,项目名称:uclapi-java,代码行数:36,代码来源:Equipment.java

示例10: asJSON

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
private JSONObject asJSON(Response response) throws Exception
{
    String json = response.getContentAsString();
    JSONParser p = new JSONParser();
    Object o = p.parse(json);
    
    if (o instanceof JSONObject)
    {
        return (JSONObject)o; 
    }
    throw new IllegalArgumentException("Expected JSONObject, got " + o + " from " + json);
}
 
开发者ID:Alfresco,项目名称:alfresco-remote-api,代码行数:13,代码来源:NodeWebScripTest.java

示例11: testPremineFromJSON

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
@Test
public void testPremineFromJSON() throws ParseException {

    JSONParser parser = new JSONParser();
    JSONObject genesisMap = (JSONObject) parser.parse(TEST_GENESIS);

    Set keys = genesisMap.keySet();

    Trie state = new TrieImpl(null, true);

    for (Object key : keys) {

        JSONObject val = (JSONObject) genesisMap.get(key);
        String denom = (String) val.keySet().toArray()[0];
        String value = (String) val.values().toArray()[0];

        BigInteger wei = Denomination.valueOf(denom.toUpperCase()).value().multiply(new BigInteger(value));

        AccountState accountState = new AccountState(BigInteger.ZERO, wei);
        byte[] encodedAccountState = accountState.getEncoded();
        byte[] accountKey = Hex.decode(key.toString());
        state = state.put(accountKey, encodedAccountState);
        Assert.assertArrayEquals(encodedAccountState, state.get(accountKey));
    }

    logger.info("root: " + Hex.toHexString(state.getHash()));
    assertEquals(GENESIS_STATE_ROOT, Hex.toHexString(state.getHash()));
}
 
开发者ID:rsksmart,项目名称:rskj,代码行数:29,代码来源:BlockTest.java

示例12: run

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
@Override
public void run()
{
	try
	{
		Messenger.sendEvent(MT.TIMER_SERVICE_CONNECTION, new Object[] { TimerClient.this, true });
		JSONParser parser = new JSONParser();

		while (!done)
		{
			String line = "";
			try 
			{
				line = in.readLine();
				log.log(Level.INFO, "TimerClient reads: {0}", line);
				if (line == null)
				{
					log.info("readLine returns null, closing connection");
					return;
				}
				
				JSONObject cmd = (JSONObject)parser.parse(line);
				String type = (String)cmd.get("type");
				
				switch (type)
				{
				    case "DIAL":
                           LeftRightDialin d = new LeftRightDialin();
                           d.decode(cmd);
                           Messenger.sendEvent(MT.TIMER_SERVICE_DIALIN, d);
                           break;
				    case "RUN":
                              Run r = new Run(0.0);
                              r.decode(cmd);
                              Messenger.sendEvent(MT.TIMER_SERVICE_RUN, r);
                              break;
				    case "RDELETE":
                        Run dr = new Run(0.0);
                        dr.decode(cmd);
                        Messenger.sendEvent(MT.TIMER_SERVICE_DELETE, dr);
                        break;
				    default:
				        log.warning("Unknown message type: " + type);
				        break;
				}
			}
			catch (ParseException pe)
			{
				log.warning(String.format("TimerClient got bad data: %s (%s)", line, pe));
			}
		}
	}
	catch (IOException ex)
	{
		log.log(Level.INFO, "read failure: " + ex, ex);
	}
	catch (Exception e)
	{
		log.log(Level.WARNING, "Unexpected timer connection failure: " + e, e);
	}
	finally
	{
		try { sock.close(); } catch (IOException ioe)  {}
		Messenger.sendEvent(MT.TIMER_SERVICE_CONNECTION, new Object[] { TimerClient.this, false });
	}
}
 
开发者ID:drytoastman,项目名称:scorekeeperfrontend,代码行数:67,代码来源:TimerClient.java

示例13: testHandleSetChildNodes2

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
/**
 * Test of {@code handleSetChildNodes} method.
 */
@Test
public void testHandleSetChildNodes2() throws ParseException {
    TransportImplementation transport = new DummyTransportImplementation();
    DOM dom = new DOM(new TransportHelper(transport), null);
    final String childName = "HTML"; // NOI18N
    final String childChildName1 = "HEAD"; // NOI18N
    final String childChildName2 = "BODY"; // NOI18N
    final Node root = dom.getDocument();
    final int[] eventsFired = new int[1];
    DOM.Listener listener = new DOMAdapter() {
        @Override
        public void childNodesSet(Node parent) {
            eventsFired[0]++;

            // Root
            assertEquals(root, parent);
            List<Node> children = parent.getChildren();
            assertNotNull(children);
            assertEquals(1, children.size());

            // Child
            Node child = children.get(0);
            assertEquals(childName, child.getNodeName());
            assertEquals(org.w3c.dom.Node.ELEMENT_NODE, child.getNodeType());
            children = child.getChildren();
            assertNotNull(children);
            assertEquals(2, children.size());

            // 1st child of the child
            child = children.get(0);
            assertEquals(childChildName1, child.getNodeName());
            assertEquals(org.w3c.dom.Node.ELEMENT_NODE, child.getNodeType());
            assertNull(child.getChildren());

            // 2nd child
            child = children.get(1);
            assertEquals(childChildName2, child.getNodeName());
            assertEquals(org.w3c.dom.Node.ELEMENT_NODE, child.getNodeType());
            assertNull(child.getChildren());
        }
    };
    dom.addListener(listener);
    JSONParser parser = new JSONParser();

    Object json = parser.parse("{\"parentId\":" + ROOT_NODE_ID + // NOI18N
            ",\"nodes\":[{\"childNodeCount\":2,\"nodeId\":2,\"localName\":\"html\",\"nodeValue\":\"\",\"nodeName\":\"" + // NOI18N
            childName + "\",\"children\":[{\"childNodeCount\":0,\"nodeId\":3,\"localName\":\"head\",\"nodeValue\":\"\",\"nodeName\":\"" + // NOI18N
            childChildName1 + "\",\"attributes\":[],\"nodeType\":1},{\"childNodeCount\":0,\"nodeId\":4,\"localName\":\"body\",\"nodeValue\":\"\",\"nodeName\":\"" + // NOI18N
            childChildName2 +"\",\"attributes\":[],\"nodeType\":1}],\"nodeType\":1}]}"); // NOI18N
    assertNull(root.getChildren());
    dom.handleSetChildNodes((JSONObject)json);
    assertEquals(1, eventsFired[0]);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:57,代码来源:DOMTest.java

示例14: sendMessage

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
protected Result sendMessage(Constants.RequestPath requestPath, String message) throws IOException, ParseException {
    HttpURLConnection conn;
    int status;
    try {
        logger.fine("post to: " + requestPath.getPath());
        conn = this.doPost(requestPath, message);
        status = conn.getResponseCode();
    } catch (IOException var11) {
        logger.log(Level.WARNING, "IOException send message: remote server " + this.remoteHost + "(" + this.remoteIp + ")", var11);
        return null;
    }

    if(status / 100 == 5) {
        logger.fine("XmPush service is unavailable (status " + status + "): remote server " + this.remoteHost + "(" + this.remoteIp + ")");
        return null;
    } else {
        String responseBody;
        if(status != 200) {
            try {
                responseBody = getAndClose(conn.getErrorStream());
                logger.finest("Plain post error response: " + responseBody);
            } catch (IOException var8) {
                responseBody = "N/A";
                logger.log(Level.FINE, "Exception reading response: ", var8);
            }

            throw new InvalidRequestException(status, responseBody);
        } else {
            try {
                responseBody = getAndClose(conn.getInputStream());
            } catch (IOException var10) {
                logger.log(Level.WARNING, "Exception reading response: remote server " + this.remoteHost + "(" + this.remoteIp + ")", var10);
                return null;
            }

            try {
                JSONParser e = new JSONParser();
                JSONObject json = (JSONObject)e.parse(responseBody);
                return (new Result.Builder()).fromJson(json);
            } catch (ParseException var9) {
                logger.log(Level.WARNING, "Exception parsing response: remote server " + this.remoteHost + "(" + this.remoteIp + ")", var9);
                throw new IOException("Invalid response from XmPush: " + responseBody);
            }
        }
    }
}
 
开发者ID:marlonwang,项目名称:raven,代码行数:47,代码来源:Subscription.java

示例15: execute

import org.json.simple.parser.JSONParser; //导入方法依赖的package包/类
@Override
public void execute(MessageReceivedEvent event, String[] args) {
    StringBuilder builder = new StringBuilder();
    for(String s : args) {
        if (builder.length() == 0) {
            builder.append(s);
        } else {
            builder.append(" ").append(s);
        }
    }

    HttpUrl url = new HttpUrl.Builder()
            .scheme("https")
            .host("rightgif.com")
            .addPathSegments("search/web")
            .build();
    FormBody body = new FormBody.Builder()
            .add("text", builder.toString())
            .build();
    Request request = new Request.Builder()
            .url(url)
            .post(body)
            .build();

    try {
        String result = client.newCall(request).execute().body().string();
        JSONParser parser = new JSONParser();
        JSONObject object = (JSONObject) parser.parse(result);
        event.getChannel().sendMessage(object.get("url").toString()).queue();
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
    /*HttpUrl url = new HttpUrl.Builder()
            .scheme("http")
            .host("api.giphy.com")
            .addPathSegments("v1/gifs/search")
            .addQueryParameter("q", builder.toString())
            .addQueryParameter("api_key", props.getProperty("giphy.key"))
            .addQueryParameter("limit", "1")
            .addQueryParameter("rating", "pg")
            .build();
    Request request = new Request.Builder().url(url).build();
    try {
        String result = client.newCall(request).execute().body().string();
        try {
            JSONParser parser = new JSONParser();
            JSONObject json = (JSONObject) parser.parse(result);
            JSONArray array = (JSONArray) json.get("data");
            JSONObject obj = (JSONObject) array.get(0);
            String gif = (String) ((JSONObject)((JSONObject)obj.get("images")).get("fixed_height")).get("url");
            event.getChannel().sendMessage(gif).queue();
        } catch (IndexOutOfBoundsException | NullPointerException e) {
            e.printStackTrace();
            event.getChannel().sendMessage("No gif found for " + builder.toString() + "!").queue();
        }

    } catch (ParseException | IOException e) {
        e.printStackTrace();
        getBot().getStacktraceHandler().sendStacktrace(e, "guildId:" + event.getGuild().getId(), "request:" + builder.toString());
    }*/
}
 
开发者ID:greatman,项目名称:legendarybot,代码行数:62,代码来源:GifCommand.java


注:本文中的org.json.simple.parser.JSONParser.parse方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。