类org.json.simple.JSONValue源码实例Demo

下面列出了怎么用org.json.simple.JSONValue的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: seppuku   文件: NetworkUtil.java
public static String resolveUsername(UUID id) {
    final String url = "https://api.mojang.com/user/profiles/" + id.toString().replace("-", "") + "/names";
    try {
        final String nameJson = IOUtils.toString(new URL(url));
        if (nameJson != null && nameJson.length() > 0) {
            final JSONArray jsonArray = (JSONArray) JSONValue.parseWithException(nameJson);
            if (jsonArray != null) {
                final JSONObject latestName = (JSONObject) jsonArray.get(jsonArray.size() - 1);
                if (latestName != null) {
                    return latestName.get("name").toString();
                }
            }
        }
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
    return null;
}
 
源代码2 项目: jolie   文件: JsUtils.java
public static void parseNdJsonIntoValue( BufferedReader reader, Value value, boolean strictEncoding )
	throws IOException {
	List< String > stringItemVector = reader.lines().collect( Collectors.toList() );

	for( String stringItem : stringItemVector ) {
		StringReader itemReader = new StringReader( stringItem );
		try {
			Value itemValue = Value.create();
			Object obj = JSONValue.parseWithException( itemReader );
			if( obj instanceof JSONArray ) {
				itemValue.children().put( JSONARRAY_KEY,
					jsonArrayToValueVector( (JSONArray) obj, strictEncoding ) );
			} else if( obj instanceof JSONObject ) {
				jsonObjectToValue( (JSONObject) obj, itemValue, strictEncoding );
			} else {
				objectToBasicValue( obj, itemValue );
			}
			value.getChildren( "item" ).add( itemValue );
		} catch( ParseException | ClassCastException e ) {
			throw new IOException( e );
		}

	}

}
 
源代码3 项目: singleton   文件: ResponseUtil.java
public static Object getMessagesFromResponse(String responseStr, String node) {
    Object msgObject = null;
    if (responseStr == null || responseStr.equalsIgnoreCase(""))
        return msgObject;
    try {
        JSONObject responseObj = (JSONObject) JSONValue
                .parseWithException(responseStr);
        if (responseObj != null) {
            JSONObject dataObj = (JSONObject) responseObj
                    .get(ConstantsForTest.DATA);
            if (dataObj != null) {
                msgObject = dataObj.get(node);
            }
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return msgObject;
}
 
源代码4 项目: jbake   文件: MarkupEngine.java
void storeHeaderValue(String inputKey, String inputValue, Map<String, Object> content) {
    String key = sanitize(inputKey);
    String value = sanitize(inputValue);

    if (key.equalsIgnoreCase(Crawler.Attributes.DATE)) {
        DateFormat df = new SimpleDateFormat(configuration.getDateFormat());
        try {
            Date date = df.parse(value);
            content.put(key, date);
        } catch (ParseException e) {
            LOGGER.error("unable to parse date {}", value);
        }
    } else if (key.equalsIgnoreCase(Crawler.Attributes.TAGS)) {
        content.put(key, getTags(value));
    } else if (isJson(value)) {
        content.put(key, JSONValue.parse(value));
    } else {
        content.put(key, value);
    }
}
 
源代码5 项目: nomulus   文件: FlowReporter.java
/** Records information about the current flow execution in the GAE request logs. */
public void recordToLogs() {
  // Explicitly log flow metadata separately from the EPP XML itself so that it stays compact
  // enough to be sure to fit in a single log entry (the XML part in rare cases could be long
  // enough to overflow into multiple log entries, breaking routine parsing of the JSON format).
  String singleTargetId = eppInput.getSingleTargetId().orElse("");
  ImmutableList<String> targetIds = eppInput.getTargetIds();
  logger.atInfo().log(
      "%s: %s",
      METADATA_LOG_SIGNATURE,
      JSONValue.toJSONString(
          new ImmutableMap.Builder<String, Object>()
              .put("serverTrid", trid.getServerTransactionId())
              .put("clientId", clientId)
              .put("commandType", eppInput.getCommandType())
              .put("resourceType", eppInput.getResourceType().orElse(""))
              .put("flowClassName", flowClass.getSimpleName())
              .put("targetId", singleTargetId)
              .put("targetIds", targetIds)
              .put("tld", eppInput.isDomainType() ? extractTld(singleTargetId).orElse("") : "")
              .put("tlds", eppInput.isDomainType() ? extractTlds(targetIds).asList() : EMPTY_LIST)
              .put("icannActivityReportField", extractActivityReportField(flowClass))
              .build()));
}
 
源代码6 项目: carbon-apimgt   文件: URITemplate.java
public String getResourceMap(){
    Map verbs = new LinkedHashMap();
    int i = 0;
    for (String method : httpVerbs) {
        Map verb = new LinkedHashMap();
        verb.put("auth_type",authTypes.get(i));
        verb.put("throttling_tier",throttlingTiers.get(i));
        //Following parameter is not required as it not need to reflect UI level. If need please enable it.
        // /verb.put("throttling_conditions", throttlingConditions.get(i));
        try{
            Scope tmpScope = scopes.get(i);
            if(tmpScope != null){
                verb.put("scope",tmpScope.getKey());
            }
        }catch(IndexOutOfBoundsException e){
            //todo need to rewrite to prevent this type of exceptions
        }
        verbs.put(method,verb);
        i++;
    }
    //todo this is a hack to make key validation service stub from braking need to rewrite.
    return JSONValue.toJSONString(verbs);
}
 
源代码7 项目: netbeans   文件: RestJSONResponseParser.java
/**
 * Parse JSON response.
 * <p/>
 * @param in {@link InputStream} to read.
 * @return Response returned by REST administration service.
 */
@Override
public RestActionReport parse(InputStream in) {
    RestActionReport report = new RestActionReport();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        copy(in, out);
        String respMsg = out.toString("UTF-8");
        JSONObject json = (JSONObject)JSONValue.parseWithException(respMsg);
        parseReport(report, json);
    } catch (IOException ex) {
        throw new PayaraIdeException("Unable to copy JSON response.", ex);
    } catch (ParseException e) {
        throw new PayaraIdeException("Unable to parse JSON response.", e);
    }
    return report;
}
 
源代码8 项目: netbeans   文件: RestJSONResponseParser.java
/**
 * Parse JSON response.
 * <p/>
 * @param in {@link InputStream} to read.
 * @return Response returned by REST administration service.
 */
@Override
public RestActionReport parse(InputStream in) {
    RestActionReport report = new RestActionReport();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        copy(in, out);
        String respMsg = out.toString("UTF-8");
        JSONObject json = (JSONObject)JSONValue.parseWithException(respMsg);
        parseReport(report, json);
    } catch (IOException ex) {
        throw new GlassFishIdeException("Unable to copy JSON response.", ex);
    } catch (ParseException e) {
        throw new GlassFishIdeException("Unable to parse JSON response.", e);
    }
    return report;
}
 
源代码9 项目: netbeans   文件: IOSDebugTransport.java
private JSONObject extractResponse(NSObject r) throws Exception {
    if (r == null) {
        return null;
    }
    if (!(r instanceof NSDictionary)) {
        return null;
    }
    NSDictionary root = (NSDictionary) r;
    NSDictionary argument = (NSDictionary) root.objectForKey("__argument"); // NOI18N
    if (argument == null) {
        return null;
    }
    NSData data = (NSData) argument.objectForKey("WIRMessageDataKey"); // NOI18N
    if (data == null) {
        return null;
    }
    byte[] bytes = data.bytes();
    String s = new String(bytes);
    JSONObject o = (JSONObject) JSONValue.parseWithException(s);
    return o;
}
 
源代码10 项目: openhab1-addons   文件: JointSpaceBinding.java
/**
 * Function to query the TV Volume
 *
 * @param host
 * @return struct containing all given information about current volume
 *         settings (volume, mute, min, max) @see volumeConfig
 */

private volumeConfig getTVVolume(String host) {
    volumeConfig conf = new volumeConfig();
    String url = "http://" + host + "/1/audio/volume";
    String volume_json = HttpUtil.executeUrl("GET", url, IOUtils.toInputStream(""), CONTENT_TYPE_JSON, 1000);
    if (volume_json != null) {
        try {
            Object obj = JSONValue.parse(volume_json);
            JSONObject array = (JSONObject) obj;

            conf.mute = Boolean.parseBoolean(array.get("muted").toString());
            conf.volume = Integer.parseInt(array.get("current").toString());
            conf.min = Integer.parseInt(array.get("min").toString());
            conf.max = Integer.parseInt(array.get("max").toString());
        } catch (NumberFormatException ex) {
            logger.warn("Exception while interpreting volume json return");
        } catch (Throwable t) {
            logger.warn("Could not parse JSON String for volume value. Error: {}", t.toString());
        }

    }
    return conf;
}
 
@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));
}
 
源代码12 项目: desktopclient-java   文件: Chat.java
private ViewSettings(String json) {
    Object obj = JSONValue.parse(json);
    Color color;
    String imagePath;
    try {
        Map<?, ?> map = (Map) obj;
        color = map.containsKey(JSON_BG_COLOR) ?
            new Color(((Long) map.get(JSON_BG_COLOR)).intValue()) :
            null;
        imagePath = map.containsKey(JSON_IMAGE_PATH) ?
            (String) map.get(JSON_IMAGE_PATH) :
            "";
    } catch (NullPointerException | ClassCastException ex) {
        LOGGER.log(Level.WARNING, "can't parse JSON view settings", ex);
        color = null;
        imagePath = "";
    }
    mColor = color;
    mImagePath = imagePath;
}
 
@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;
}
 
源代码14 项目: teamcity-oauth   文件: GithubUser.java
private Set<String> fetchUserOrganizations() {
    String response = organizationSupplier.get();
    log.debug("Fetched user org data: " + response);
    Object parsedResponse = JSONValue.parse(response);
    if (parsedResponse instanceof JSONArray) {
        return ((List<Object>) parsedResponse)
                .stream()
                .filter(item -> item instanceof JSONObject)
                .map(item -> ((JSONObject) item).get("login"))
                .filter(Objects::nonNull)
                .map(Object::toString)
                .collect(Collectors.toSet());
    } else {
        String message = ((JSONObject) parsedResponse).getOrDefault("message", "Incorrect response:" + response ).toString();
        throw new IllegalStateException(message);
    }
}
 
源代码15 项目: BiglyBT   文件: JSONUtils.java
/**
 * decodes JSON formatted text into a map.
 *
 * @return Map parsed from a JSON formatted string
 * <p>
 *  If the json text is not a map, a map with the key "value" will be returned.
 *  the value of "value" will either be an List, String, Number, Boolean, or null
 *  <p>
 *  if the String is formatted badly, null is returned
 */
public static Map decodeJSON(String json) {
	try {
		Object object = JSONValue.parse(json);
		if (object instanceof Map) {
			return (Map) object;
		}
		// could be : ArrayList, String, Number, Boolean
		Map map = new HashMap();
		map.put("value", object);
		return map;
	} catch (Throwable t) {
		Debug.out("Warning: Bad JSON String: " + json, t);
		return null;
	}
}
 
源代码16 项目: cloudsimsdn   文件: PhysicalTopologyParser.java
public Map<String, String> parseDatacenters() {
	HashMap<String, String> dcNameType = new HashMap<String, String>();
	try {
   		JSONObject doc = (JSONObject) JSONValue.parse(new FileReader(this.filename));
   		
   		JSONArray datacenters = (JSONArray) doc.get("datacenters");
   		@SuppressWarnings("unchecked")
		Iterator<JSONObject> iter = datacenters.iterator(); 
		while(iter.hasNext()){
			JSONObject node = iter.next();
			String dcName = (String) node.get("name");
			String type = (String) node.get("type");
			
			dcNameType.put(dcName, type);
		}
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
	
	return dcNameType;		
}
 
源代码17 项目: scava   文件: GitHubImporter.java
private void waitApiRate() {

		String url = "https://api.github.com/rate_limit" + authString;
		boolean sleep = true;
		logger.info("API rate limit exceeded. Waiting to restart the importing...");
		while (sleep) {
			try {
				InputStream is = new URL(url).openStream();
				BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
				String jsonText = readAll(rd);

				JSONObject obj = (JSONObject) JSONValue.parse(jsonText);
				JSONObject rate = (JSONObject) ((JSONObject) obj.get("rate"));
				Integer remaining = new Integer(rate.get("remaining").toString());
				if (remaining > 0) {
					sleep = false;
				}

			} catch (IOException e) {
				logger.error("Having difficulties to connect, retrying...");
				continue;
			}
		}
	}
 
源代码18 项目: leaf-snowflake   文件: Utils.java
public static Map readCommandLineOpts() {
	Map ret = new HashMap();
	String commandOptions = System.getProperty("leaf.options");
	if (commandOptions != null) {
		String[] configs = commandOptions.split(",");
		for (String config : configs) {
			config = URLDecoder.decode(config);
			String[] options = config.split("=", 2);
			if (options.length == 2) {
				Object val = JSONValue.parse(options[1]);
				if (val == null) {
					val = options[1];
				}
				ret.put(options[0], val);
			}
		}
	}
	return ret;
}
 
源代码19 项目: UltimateChat   文件: UltimateFancy.java
public UltimateFancy appendString(String jsonObject) {
    Object obj = JSONValue.parse(jsonObject);
    if (obj instanceof JSONObject) {
        workingGroup.add((JSONObject) obj);
    }
    if (obj instanceof JSONArray) {
        for (Object object : ((JSONArray) obj)) {
            if (object.toString().isEmpty()) continue;
            if (object instanceof JSONArray) {
                appendString(object.toString());
            } else {
                workingGroup.add((JSONObject) JSONValue.parse(object.toString()));
            }
        }
    }
    return this;
}
 
源代码20 项目: wisdom   文件: NPM.java
/**
 * Utility method to extract the version from a NPM by reading its 'package.json' file.
 *
 * @param npmDirectory the directory in which the NPM is installed
 * @param log          the logger object
 * @return the read version, "0.0.0" if there are not 'package.json' file, {@code null} if this file cannot be
 * read or does not contain the "version" metadata
 */
public static String getVersionFromNPM(File npmDirectory, Log log) {
    File packageFile = new File(npmDirectory, PACKAGE_JSON);
    if (!packageFile.isFile()) {
        return "0.0.0";
    }

    FileReader reader = null;
    try {
        reader = new FileReader(packageFile);  //NOSONAR
        JSONObject json = (JSONObject) JSONValue.parseWithException(reader);
        return (String) json.get("version");
    } catch (IOException | ParseException e) {
        log.error("Cannot extract version from " + packageFile.getAbsolutePath(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    return null;
}
 
源代码21 项目: The-5zig-Mod   文件: JSONWriter.java
public void writeObject(Object obj) throws IOException {
	if ((obj instanceof JSONObject)) {
		JSONObject jObj = (JSONObject) obj;
		writeJsonObject(jObj);
		return;
	}
	if ((obj instanceof JSONArray)) {
		JSONArray jArr = (JSONArray) obj;
		writeJsonArray(jArr);
		return;
	}
	this.writer.write(JSONValue.toJSONString(obj));
}
 
源代码22 项目: The-5zig-Mod   文件: JSONWriter.java
private void writeJsonObject(JSONObject jObj) throws IOException {
	writeLine("{");
	indentAdd();

	Set keys = jObj.keySet();
	int keyNum = keys.size();
	int count = 0;
	for (Iterator it = keys.iterator(); it.hasNext(); ) {
		String key = (String) it.next();
		Object val = jObj.get(key);

		writeIndent();
		this.writer.write(JSONValue.toJSONString(key));
		this.writer.write(": ");

		writeObject(val);

		count++;
		if (count < keyNum) {
			writeLine(",");
		} else {
			writeLine("");
		}
	}
	indentRemove();
	writeIndent();
	this.writer.write("}");
}
 
源代码23 项目: sakai   文件: LTI13JwtUtil.java
public static JSONObject jsonJwtHeader(String id_token) {
	String headerStr = rawJwtHeader(id_token);

	if ( headerStr == null ) return null;
	Object headerObj = JSONValue.parse(headerStr);
	if ( headerObj == null ) return null;
	if ( ! ( headerObj instanceof JSONObject) ) return null;
	return (JSONObject) headerObj;
}
 
源代码24 项目: The-5zig-Mod   文件: JSONWriter.java
private void writeJsonObject(JSONObject jObj) throws IOException {
	writeLine("{");
	indentAdd();

	Set keys = jObj.keySet();
	int keyNum = keys.size();
	int count = 0;
	for (Iterator it = keys.iterator(); it.hasNext(); ) {
		String key = (String) it.next();
		Object val = jObj.get(key);

		writeIndent();
		this.writer.write(JSONValue.toJSONString(key));
		this.writer.write(": ");

		writeObject(val);

		count++;
		if (count < keyNum) {
			writeLine(",");
		} else {
			writeLine("");
		}
	}
	indentRemove();
	writeIndent();
	this.writer.write("}");
}
 
源代码25 项目: nomulus   文件: CreateOrUpdatePremiumListCommand.java
private String extractServerResponse(String response) {
  Map<String, Object> responseMap = toMap(JSONValue.parse(stripJsonPrefix(response)));

  // TODO(user): consider using jart's FormField Framework.
  // See: j/c/g/d/r/ui/server/RegistrarFormFields.java
  String status = (String) responseMap.get("status");
  Verify.verify(!status.equals("error"), "Server error: %s", responseMap.get("error"));
  return String.format("Successfully saved premium list %s\n", name);
}
 
源代码26 项目: sqoop-on-spark   文件: IntermediateDataFormat.java
/**
 * Provide the external jars that the IDF depends on
 * @return set of jars
 */
public Set<String> getJars() {
  Set<String> jars = new  HashSet<String>();
  // Add JODA classes for IDF date/time handling
  jars.add(ClassUtils.jarForClass(LocalDate.class));
  jars.add(ClassUtils.jarForClass(LocalDateTime.class));
  jars.add(ClassUtils.jarForClass(DateTime.class));
  jars.add(ClassUtils.jarForClass(LocalTime.class));
  // Add JSON parsing jar
  jars.add(ClassUtils.jarForClass(JSONValue.class));
  return jars;
}
 
源代码27 项目: jcoSon   文件: jcoSon.java
/**
 *
 * @param destination A valid JCo Destination
 * @return json Representation of the JCo Function call
 * @throws JCoException
 */
public String execute(JCoDestination destination) throws JCoException
{
    LinkedHashMap resultList = new LinkedHashMap();
    try
    {
        function.execute(destination);
    }
    catch(AbapException e)
    {
       resultList.put(e.getKey(),e);
    }
    catch (JCoException ex)
    {
        resultList.put(ex.getKey(),ex);
    }
    //Export Parameters
    if(function.getExportParameterList()!= null)
    {
        getFields(function.getExportParameterList().getFieldIterator(),resultList);
    }
    //Changing parameters
    if(function.getChangingParameterList()!= null)
    {
        getFields(function.getChangingParameterList().getFieldIterator(),resultList);
    }
    //Table Parameters
    if(function.getTableParameterList()!= null)
    {
        getFields(function.getTableParameterList().getFieldIterator(),resultList);
    }
    return JSONValue.toJSONString(resultList);
}
 
源代码28 项目: ethereumj   文件: Op.java
public String toString(){

        Map<Object, Object> jsonData = new LinkedHashMap<>();

        jsonData.put("op", OpCode.code(op).name());
        jsonData.put("pc", Long.toString(pc));
        jsonData.put("gas", gas.value().toString());
        jsonData.put("stack", stack);
        jsonData.put("memory", memory == null ? "" : Hex.toHexString(memory));
        jsonData.put("storage", new JSONObject(storage)  );

        return JSONValue.toJSONString(jsonData);
    }
 
源代码29 项目: desktopclient-java   文件: KonMessage.java
static ServerError fromJSON(String jsonContent) {
    Object obj = JSONValue.parse(jsonContent);
    Map<?, ?> map = (Map) obj;
    if (map == null) return new ServerError();
    String condition = EncodingUtils.getJSONString(map, JSON_COND);
    String text = EncodingUtils.getJSONString(map, JSON_TEXT);
    return new ServerError(condition, text);
}
 
源代码30 项目: netbeans   文件: NewSampleWizardIterator.java
private static void filterJson(FileObject fo, String name) throws IOException {
    Path path = FileUtil.toFile(fo).toPath();
    Charset charset = StandardCharsets.UTF_8;
    String content = new String(Files.readAllBytes(path), charset);
    content = content.replace("${project.name}", JSONValue.escape(name)); // NOI18N
    Files.write(path, content.getBytes(charset));
}