本文整理了Java中com.eclipsesource.json.JsonObject
类的一些代码示例,展示了JsonObject
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JsonObject
类的具体详情如下:
包路径:com.eclipsesource.json.JsonObject
类名称:JsonObject
[英]Represents a JSON object, i.e. an unordered set of name/value pairs, where the names are strings and the values are JSON values.
Members can be added using the add(String, ...)
methods which accept instances of JsonValue, strings, primitive numbers, and boolean values. To modify certain values of an object, use the set(String, ...)
methods. Please note that the add
methods are faster than set
as they do not search for existing members. On the other hand, the add
methods do not prevent adding multiple members with the same name. Duplicate names are discouraged but not prohibited by JSON.
Members can be accessed by their name using #get(String). A list of all names can be obtained from the method #names(). This class also supports iterating over the members in document order using an #iterator() or an enhanced for loop:
for( Member member : jsonObject ) {
String name = member.getName();
JsonValue value = member.getValue();
...
}
Even though JSON objects are unordered by definition, instances of this class preserve the order of members to allow processing in document order and to guarantee a predictable output.
Note that this class is not thread-safe. If multiple threads access a JsonObject
instance concurrently, while at least one of these threads modifies the contents of this object, access to the instance must be synchronized externally. Failure to do so may lead to an inconsistent state.
This class is not supposed to be extended by clients.
[中]表示JSON对象,即无序的名称/值对集,其中名称为字符串,值为JSON值。
可以使用add(String, ...)
方法添加成员,这些方法接受JsonValue、字符串、基元数和布尔值的实例。要修改对象的某些值,请使用set(String, ...)
方法。请注意add
方法比set
更快,因为它们不搜索现有成员。另一方面,add
方法并不阻止添加具有相同名称的多个成员。JSON不鼓励重复名称,但不禁止重复名称。
可以使用#get(String)通过其名称访问成员。可以通过方法#names()获得所有名称的列表。此类还支持使用#迭代器()或增强的for循环按文档顺序迭代成员:
for( Member member : jsonObject ) {
String name = member.getName();
JsonValue value = member.getValue();
...
}
尽管JSON对象在定义上是无序的,但该类的实例保留了成员的顺序,以允许按文档顺序处理,并保证可预测的输出。
请注意,此类不是线程安全的。如果多个线程同时访问JsonObject
实例,而其中至少一个线程修改此对象的内容,则必须从外部同步对该实例的访问。不这样做可能会导致状态不一致。
这个类不应该被客户端扩展。
代码示例来源:origin: Vedenin/useful-java-links
public static void main(String[] args) throws IOException {
// convert Java to writer
JsonObject root = Json.object().add("message", "Hi").add(
"place", Json.object().add("name", "World!")
);
StringWriter writer = new StringWriter();
root.writeTo(writer);
String json = writer.toString();
System.out.println(json);
System.out.println();
// convert writer to Java
JsonObject obj = Json.parse(json).asObject();
String message = obj.get("message").asString();
String name = obj.get("place").asObject().get("name").asString();
System.out.println(message + " " + name);
}
}
代码示例来源:origin: ralfstx/minimal-json
private static JsonObject extractMeasurement(JsonObject measurement) {
JsonObject times = measurement.get("v").asObject()
.get("measurementSetMap").asObject()
.get("TIME").asObject();
return new JsonObject().add("variables", measurement.get("k").asObject().get("variables"))
.add("units", times.get("unitNames"))
.add("values", extractTimes(times.get("measurements").asArray()));
}
代码示例来源:origin: ralfstx/minimal-json
/**
* Sets the value of the member with the specified name to the JSON representation of the
* specified <code>long</code> value. If this object does not contain a member with this name, a
* new member is added at the end of the object. If this object contains multiple members with
* this name, only the last one is changed.
* <p>
* This method should <strong>only be used to modify existing objects</strong>. To fill a new
* object with members, the method <code>add(name, value)</code> should be preferred which is much
* faster (as it does not need to search for existing members).
* </p>
*
* @param name
* the name of the member to replace
* @param value
* the value to set to the member
* @return the object itself, to enable method chaining
*/
public JsonObject set(String name, long value) {
set(name, Json.value(value));
return this;
}
代码示例来源:origin: libgdx/packr
JsonObject json = JsonObject.readFrom(FileUtils.readFileToString(configJson));
if (json.get("platform") != null) {
platform = Platform.byDesc(json.get("platform").asString());
if (json.get("jdk") != null) {
jdk = json.get("jdk").asString();
if (json.get("executable") != null) {
executable = json.get("executable").asString();
if (json.get("classpath") != null) {
classpath = toStringArray(json.get("classpath").asArray());
if (json.get("removelibs") != null) {
removePlatformLibs = toStringArray(json.get("removelibs").asArray());
if (json.get("mainclass") != null) {
mainClass = json.get("mainclass").asString();
if (json.get("vmargs") != null) {
List<String> vmArgs = toStringArray(json.get("vmargs").asArray());
this.vmArgs = new ArrayList<>();
for (String vmArg : vmArgs) {
if (json.get("minimizejre") != null) {
minimizeJre = json.get("minimizejre").asString();
if (json.get("cachejre") != null) {
代码示例来源:origin: ralfstx/minimal-json
@Override
protected void setUp() throws IOException {
jsonObject = new JsonObject();
for (int index = 0; index < size; index++) {
String name = Integer.toHexString(index);
jsonObject.add(name, index);
}
}
代码示例来源:origin: BTCPrivate/bitcoin-private-full-node-wallet
private void decomposeJSONValue(String name, JsonValue val, Map<String, String> map) {
if (val.isObject()) {
JsonObject obj = val.asObject();
for (String memberName : obj.names()) {
this.decomposeJSONValue(name + "." + memberName, obj.get(memberName), map);
}
} else if (val.isArray()) {
JsonArray arr = val.asArray();
for (int i = 0; i < arr.size(); i++) {
this.decomposeJSONValue(name + "[" + i + "]", arr.get(i), map);
}
} else {
map.put(name, val.toString());
}
}
代码示例来源:origin: ralfstx/minimal-json
private static JsonValue extractTimes(JsonArray measurements) {
JsonArray result = new JsonArray();
for (JsonValue measurement : measurements) {
result.add(measurement.asObject().get("processed"));
}
return result;
}
代码示例来源:origin: box/box-java-sdk
/**
* {@inheritDoc}
*/
@Override
void parseJSONMember(JsonObject.Member member) {
super.parseJSONMember(member);
String memberName = member.getName();
JsonValue value = member.getValue();
try {
if (memberName.equals("assigned_to")) {
JsonObject assignmentJSON = value.asObject();
this.assignedToType = assignmentJSON.get("type").asString();
this.assignedToID = assignmentJSON.get("id").asString();
} else if (memberName.equals("storage_policy")) {
JsonObject storagePolicyJSON = value.asObject();
this.storagePolicyID = storagePolicyJSON.get("id").asString();
this.storagePolicyType = storagePolicyJSON.get("type").asString();
}
} catch (ParseException e) {
assert false : "A ParseException indicates a bug in the SDK.";
}
}
}
代码示例来源:origin: eclipse/leshan
public static Observation deserialize(byte[] data) {
JsonObject v = (JsonObject) Json.parse(new String(data));
EndpointContext endpointContext = EndpointContextSerDes.deserialize(v.get("peer").asObject());
byte[] req = Hex.decodeHex(v.getString("request", null).toCharArray());
RawData rawData = RawData.outbound(req, endpointContext, null, false);
Request request = (Request) parser.parseMessage(rawData);
request.setDestinationContext(endpointContext);
JsonValue ctxValue = v.get("context");
if (ctxValue != null) {
Map<String, String> context = new HashMap<>();
JsonObject ctxObject = (JsonObject) ctxValue;
for (String name : ctxObject.names()) {
context.put(name, ctxObject.getString(name, null));
}
request.setUserContext(context);
}
return new Observation(request, endpointContext);
}
代码示例来源:origin: org.wildfly.swarm/fraction-metadata
private void addDependencies(JsonObject fraction, FractionDescriptor parent) {
fraction.get("fractionDependencies").asArray().forEach(entry -> {
JsonObject dependency = entry.asObject();
FractionDescriptor descriptor = getFractionDescriptor(dependency);
if (parent != null) {
parent.addDependency(descriptor);
}
addDependencies(dependency, descriptor);
});
}
代码示例来源:origin: eclipse/leshan
private void sendError(String ticket, String message) {
try (Jedis j = pool.getResource()) {
JsonObject m = Json.object();
m.add("ticket", ticket);
JsonObject err = Json.object();
err.add("errorMessage", message);
m.add("err", err);
j.publish(RESPONSE_CHANNEL, m.toString());
}
}
代码示例来源:origin: samczsun/Skype4J
public static String upload(byte[] data, ImageType type, JsonObject extra, ChatImpl chat) throws ConnectionException {
JsonObject obj = new JsonObject();
obj.add("type", type.mime);
obj.add("permissions", new JsonObject().add(chat.getIdentity(), new JsonArray().add("read")));
if (extra != null) extra.forEach(m -> obj.add(m.getName(), m.getValue()));
JsonObject response = Endpoints.OBJECTS
.open(chat.getClient())
.as(JsonObject.class)
.expect(201, "While uploading data")
.post(obj);
String id = response.get("id").asString();
Endpoints.UPLOAD_IMAGE
.open(chat.getClient(), id, type.endpoint)
.header("Content-Type", "multipart/form-data")
.expect(201, "While uploading data")
.connect("PUT", data);
Endpoints.EndpointConnection<JsonObject> econn = Endpoints.IMG_STATUS
.open(chat.getClient(), id, type.id)
.as(JsonObject.class)
.expect(200, "While getting upload status");
while (true) {
JsonObject status = econn.get();
if (status.get("view_state").asString().equals("ready")) {
break;
}
}
return id;
}
代码示例来源:origin: libgdx/packr
JsonArray reduceArray = minimizeJson.get("reduce").asArray();
for (JsonValue reduce : reduceArray) {
String path = reduce.asObject().get("archive").asString();
File file = new File(output, path);
JsonArray removeArray = reduce.asObject().get("paths").asArray();
for (JsonValue remove : removeArray) {
File removeFile = new File(fileNoExt, remove.asString());
JsonArray removeArray = minimizeJson.get("remove").asArray();
for (JsonValue remove : removeArray) {
String platform = remove.asObject().get("platform").asString();
JsonArray removeFilesArray = remove.asObject().get("paths").asArray();
for (JsonValue removeFile : removeFilesArray) {
removeFileWildcard(output, removeFile.asString(), config);
代码示例来源:origin: BTCPrivate/bitcoin-private-full-node-wallet
public synchronized String[] getWalletPublicAddressesWithUnspentOutputs()
throws WalletCallException, IOException, InterruptedException {
JsonArray jsonUnspentOutputs = executeCommandAndGetJsonArray("listunspent", "0");
Set<String> addresses = new HashSet<>();
for (int i = 0; i < jsonUnspentOutputs.size(); i++) {
JsonObject outp = jsonUnspentOutputs.get(i).asObject();
addresses.add(outp.getString("address", "ERROR!"));
}
return addresses.toArray(new String[0]);
}
代码示例来源:origin: box/box-java-sdk
private BoxFileUploadSession.Info createUploadSession(BoxAPIConnection boxApi, URL url, long fileSize) {
BoxJSONRequest request = new BoxJSONRequest(boxApi, url, HttpMethod.POST);
//Creates the body of the request
JsonObject body = new JsonObject();
body.add("file_size", fileSize);
request.setBody(body.toString());
BoxJSONResponse response = (BoxJSONResponse) request.send();
JsonObject jsonObject = JsonObject.readFrom(response.getJSON());
String sessionId = jsonObject.get("id").asString();
BoxFileUploadSession session = new BoxFileUploadSession(boxApi, sessionId);
return session.new Info(jsonObject);
}
代码示例来源:origin: io.thorntail/config-api-generator
public List<GeneratorTarget> getGeneratorTargets() {
List<GeneratorTarget> references = new ArrayList<>();
json.get("generatorTargets").asArray().forEach(ref -> {
//JsonObject atts = ref.asObject();
references.add(new GeneratorTarget(ref.asString()));
});
return references;
}
代码示例来源:origin: org.eclipse.leshan/leshan-server-cluster
@Override
public void updated(RegistrationUpdate update, Registration updatedRegistration,
Registration previousRegistration) {
JsonObject value = new JsonObject();
value.add("regUpdate", RegistrationUpdateSerDes.jSerialize(update));
value.add("regUpdated", RegistrationSerDes.jSerialize(updatedRegistration));
try (Jedis j = pool.getResource()) {
j.publish(UPDATE_EVENT, value.toString());
}
}
代码示例来源:origin: samczsun/Skype4J
private static JsonObject getObject(SkypeImpl skype, String username) throws ConnectionException {
JsonArray array = Endpoints.PROFILE_INFO
.open(skype)
.expect(200, "While getting contact info")
.as(JsonArray.class)
.post(new JsonObject()
.add("usernames", new JsonArray()
.add(username)
)
);
return array.get(0).asObject();
}
代码示例来源:origin: mvetsch/JWT4B
private KeyValuePair lookForJwtInJsonObject(JsonObject object) {
KeyValuePair rec;
for (String name : object.names()) {
if (object.get(name).isString()) {
if (TokenCheck.isValidJWT(object.get(name).asString())) {
return new KeyValuePair(name, object.get(name).asString().trim());
}
} else if (object.get(name).isObject()) {
if ((rec = lookForJwtInJsonObject(object.get(name).asObject())) != null) {
return rec;
}
}
}
return null;
}
代码示例来源:origin: BTCPrivate/bitcoin-private-full-node-wallet
public synchronized String getOperationFinalErrorMessage(String opID)
throws WalletCallException, IOException, InterruptedException {
JsonArray response = this.executeCommandAndGetJsonArray(
"z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
JsonObject jsonStatus = response.get(0).asObject();
JsonObject jsonError = jsonStatus.get("error").asObject();
return jsonError.getString("message", "ERROR!");
}
内容来源于网络,如有侵权,请联系作者删除!