下面列出了怎么用com.google.gson.JsonPrimitive的API类实例代码及写法,或者点击链接到github查看源代码。
public static int checkHeavyDamagedExist() {
int status = HD_NONE;
for (int i = 0; i < friendMaxHps.size(); i++) {
if (!checkhdmgflag[i]) continue;
if (friendNowHps.get(i).getAsInt() * 4 <= friendMaxHps.get(i).getAsInt()
&& !escapelist.contains(new JsonPrimitive(i + 1))) {
if (dameconflag[i]) {
status = Math.max(status, HD_DAMECON);
} else {
status = Math.max(status, HD_DANGER);
if (status == HD_DANGER) {
return status;
}
}
}
}
return status;
}
/**
* @return Encoded JsonObject representation of PublicKeyCredentialDescriptor
*/
public JsonObject getJsonObject() {
JsonObject result = new JsonObject();
result.addProperty("type", type.toString());
result.addProperty("id", BaseEncoding.base64().encode(id));
JsonArray transports = new JsonArray();
if (this.transports != null) {
for (AuthenticatorTransport t : this.transports) {
JsonPrimitive element = new JsonPrimitive(t.toString());
transports.add(element);
}
if (transports.size() > 0) {
result.add("transports", transports);
}
}
return result;
}
public void testDeserialize() throws Exception {
String operation = "{'id':'op1','method':'wavelet.setTitle','params':{" +
"'waveId':'1','waveletId':'2','waveletTitle':'Title','unknown':'value'}}";
JsonElement jsonElement = new JsonParser().parse(operation);
JsonDeserializationContext mockContext = mock(JsonDeserializationContext.class);
when(mockContext.deserialize(any(JsonElement.class), eq(String.class))).thenAnswer(
new Answer<String>() {
public String answer(InvocationOnMock invocation) {
return ((JsonPrimitive) (invocation.getArguments()[0])).getAsString();
}
});
OperationRequestGsonAdaptor adaptor = new OperationRequestGsonAdaptor();
OperationRequest result = adaptor.deserialize(jsonElement, null, mockContext);
assertEquals("op1", result.getId());
assertEquals("wavelet.setTitle", result.getMethod());
assertEquals("1", result.getWaveId());
assertEquals("2", result.getWaveletId());
assertNull(result.getBlipId());
assertEquals(3, result.getParams().size());
assertEquals("Title", result.getParameter(ParamsProperty.WAVELET_TITLE));
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues);
}
data.add("values", values);
return data;
}
@Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP,
description = "Test Android device lock operation for invalid device id.")
public void testLockWithInvalidDeviceId() throws Exception {
JsonObject operationData = PayloadGenerator
.getJsonPayload(Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME,
Constants.AndroidOperations.LOCK_OPERATION);
JsonArray deviceIds = new JsonArray();
JsonPrimitive deviceID = new JsonPrimitive(Constants.NUMBER_NOT_EQUAL_TO_DEVICE_ID);
deviceIds.add(deviceID);
operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds);
try {
client.post(Constants.AndroidOperations.ANDROID_DEVICE_MGT_API + Constants.AndroidOperations.LOCK_ENDPOINT,
operationData.toString());
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("HTTP response code: 400"));
}
}
public String parseJavaScriptLiteral(String text, String functionIdentifier)
{
StringBuilder builder = new StringBuilder();
Matcher matcher = PLACEHOLDER_PATTERN.matcher(text);
int lastIndex = 0;
while (matcher.find())
{
String matched = new JsonPrimitive(text.substring(matcher.start() + 1, matcher.end() - 1)).toString();
builder.append(text, lastIndex, matcher.start()).append(functionIdentifier);
builder.append("(").append(matched).append(")");
lastIndex = matcher.end();
}
if (lastIndex < text.length())
{
builder.append(text.substring(lastIndex));
}
return builder.toString();
}
@Override
public void fromJsonObject(@NotNull JsonObject obj) {
if (obj.has(getName())) {
JsonElement element = obj.get(getName());
if (element instanceof JsonPrimitive && ((JsonPrimitive) element).isNumber()) {
if (getObject() instanceof Integer) {
setObject((T) Integer.valueOf(obj.get(getName()).getAsNumber().intValue()));
}
if (getObject() instanceof Long) {
setObject((T) Long.valueOf(obj.get(getName()).getAsNumber().longValue()));
}
if (getObject() instanceof Float) {
setObject((T) Float.valueOf(obj.get(getName()).getAsNumber().floatValue()));
}
if (getObject() instanceof Double) {
setObject((T) Double.valueOf(obj.get(getName()).getAsNumber().doubleValue()));
}
} else {
throw new IllegalArgumentException("Entry '" + getName() + "' is not valid");
}
} else {
throw new IllegalArgumentException("Object does not have '" + getName() + "'");
}
}
private String getEndpointUrl(JsonElement element) {
if (element == null) {
return null;
}
JsonPrimitive urlString = null;
if (element.isJsonPrimitive()) {
urlString = element.getAsJsonPrimitive();
} else {
JsonObject replicatorEndpointObject = element.getAsJsonObject();
urlString = replicatorEndpointObject.getAsJsonPrimitive("url");
}
if (urlString == null) {
return null;
}
return urlString.getAsString();
}
private static void trainOnText(String[] text, String[] label) {
List<String> labelSet = new ArrayList<>();
List<String> textSet = new ArrayList<>();
Collections.addAll(labelSet, label);
Collections.addAll(textSet, text);
JsonArray labelArray = new JsonArray();
JsonArray textArray = new JsonArray();
labelSet.forEach((s) -> labelArray.add(new JsonPrimitive(s)));
textSet.forEach((s) -> textArray.add(new JsonPrimitive(s)));
JsonObject jsonParam = new JsonObject();
jsonParam.add("text", textArray);
jsonParam.add("label", labelArray);
jsonParam.add("focus", new JsonPrimitive(2));
String jsonPayload = new Gson().toJson(jsonParam);
System.out.println(executePost("http://localhost:7474/service/graphify/training", jsonPayload));
}
@Override
protected JsonObject getChartData() throws Exception {
JsonObject data = new JsonObject();
JsonObject values = new JsonObject();
Map<String, Integer> map = callable.call();
if (map == null || map.isEmpty()) {
// Null = skip the chart
return null;
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
JsonArray categoryValues = new JsonArray();
categoryValues.add(new JsonPrimitive(entry.getValue()));
values.add(entry.getKey(), categoryValues);
}
data.add("values", values);
return data;
}
@Test
public void shouldBeAbleToConvertACommand() {
SessionId sessionId = new SessionId("some id");
String commandName = "some command";
Map<String, Object> parameters = new HashMap<>();
parameters.put("param1", "value1");
parameters.put("param2", "value2");
Command command = new Command(sessionId, commandName, parameters);
String json = convert(command);
JsonObject converted = new JsonParser().parse(json).getAsJsonObject();
assertThat(converted.has("sessionId")).isTrue();
JsonPrimitive sid = converted.get("sessionId").getAsJsonPrimitive();
assertThat(sid.getAsString()).isEqualTo(sessionId.toString());
assertThat(commandName).isEqualTo(converted.get("name").getAsString());
assertThat(converted.has("parameters")).isTrue();
JsonObject pars = converted.get("parameters").getAsJsonObject();
assertThat(pars.entrySet()).hasSize(2);
assertThat(pars.get("param1").getAsString()).isEqualTo(parameters.get("param1"));
assertThat(pars.get("param2").getAsString()).isEqualTo(parameters.get("param2"));
}
/**
* The serializer overrides field adapter, but for deserializer the fieldAdapter is used.
*/
public void testRegisteredSerializerOverridesJsonAdapter() {
JsonSerializer<A> serializer = new JsonSerializer<A>() {
public JsonElement serialize(A src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive("registeredSerializer");
}
};
Gson gson = new GsonBuilder()
.registerTypeAdapter(A.class, serializer)
.create();
String json = gson.toJson(new A("abcd"));
assertEquals("\"registeredSerializer\"", json);
A target = gson.fromJson("abcd", A.class);
assertEquals("jsonAdapter", target.value);
}
@Test(groups = Constants.AndroidOperations.OPERATIONS_GROUP,
description = "Test Android encrypt operation for invalid device id")
public void testEncryptWithInvalidDeviceId() throws Exception {
JsonObject operationData = PayloadGenerator
.getJsonPayload(Constants.AndroidOperations.OPERATION_PAYLOAD_FILE_NAME,
Constants.AndroidOperations.ENCRYPT_OPERATION);
JsonArray deviceIds = new JsonArray();
JsonPrimitive deviceID = new JsonPrimitive(Constants.NUMBER_NOT_EQUAL_TO_DEVICE_ID);
deviceIds.add(deviceID);
operationData.add(Constants.DEVICE_IDENTIFIERS_KEY, deviceIds);
try {
client.post(
Constants.AndroidOperations.ANDROID_DEVICE_MGT_API + Constants.AndroidOperations.ENCRYPT_ENDPOINT,
operationData.toString());
} catch (Exception e) {
Assert.assertTrue(e.getMessage().contains("HTTP response code: 400"));
}
}
public void handlePluginMessage(byte[] message) {
String strMessage = new String(message, StandardCharsets.UTF_8);
try (CharArrayReader reader = new CharArrayReader(strMessage.toCharArray())) {
JsonReader r = new JsonReader(reader);
r.setLenient(true);
while (r.peek() != JsonToken.END_DOCUMENT) {
r.beginObject();
JsonObject o = new JsonObject();
while (r.hasNext()) {
String name = r.nextName();
if (r.peek() == JsonToken.NUMBER)
o.add(name, new JsonPrimitive(r.nextLong()));
else
o.add(name, new JsonPrimitive(r.nextString()));
}
r.endObject();
Vote v = new Vote(o);
listener.onForward(v);
}
} catch (IOException e) {
e.printStackTrace(); // Should never happen.
}
}
@Override
public void serialize(TypeToken<?> type, JsonElement from, ConfigurationNode to) throws ObjectMappingException {
if (from.isJsonPrimitive()) {
JsonPrimitive primitive = from.getAsJsonPrimitive();
to.setValue(GsonConverters.IMMUTABLE.unwarpPrimitive(primitive));
} else if (from.isJsonNull()) {
to.setValue(null);
} else if (from.isJsonArray()) {
JsonArray array = from.getAsJsonArray();
// ensure 'to' is a list node
to.setValue(ImmutableList.of());
for (JsonElement element : array) {
serialize(TYPE, element, to.getAppendedNode());
}
} else if (from.isJsonObject()) {
JsonObject object = from.getAsJsonObject();
// ensure 'to' is a map node
to.setValue(ImmutableMap.of());
for (Map.Entry<String, JsonElement> ent : object.entrySet()) {
serialize(TYPE, ent.getValue(), to.getNode(ent.getKey()));
}
} else {
throw new ObjectMappingException("Unknown element type: " + from.getClass());
}
}
public static String getStringFieldFromJsonObject(JsonObject jsonObject, String fieldName) {
if (jsonObject == null) {
return null;
}
String returnString = null;
try {
JsonElement jsonElement = jsonObject.get(fieldName);
if (jsonElement != null) {
JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
returnString = jsonPrimitive.getAsString();
}
}
catch (Exception e) {
logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
}
return returnString;
}
public CompletableFuture<StoreAppDetails> getAppDetails(int appId, String countryCode, String language) {
CompletableFuture<JsonObject> json = sendRequest(new GetAppDetails(VERSION_1, appId, countryCode, language));
return json.thenApply(root -> {
JsonObject appObject = root.getAsJsonObject(String.valueOf(appId));
JsonPrimitive success = appObject.getAsJsonPrimitive("success");
if (success != null && success.getAsBoolean()) {
JsonObject appData = appObject.getAsJsonObject("data");
return fromJson(appData, StoreAppDetails.class);
}
return null;
});
}
@Test
public final void testCopy() {
stubFor(any(urlMatching("/"))
.willReturn(aResponse()
.withStatus(HttpURLConnection.HTTP_OK)
.withHeader("Content-Type", "application/json")
.withBody(JSON_TRUE_RESPONSE)));
LocalCall<Boolean> call = File.copy("/test1", "/test2", false, false);
assertEquals("file.copy", call.getPayload().get("fun"));
Map<String, Result<Boolean>> response = call.callSync(client,
new MinionList("minion1"), AUTH).toCompletableFuture().join();
assertTrue(response.get("minion1").result().get());
stubFor(any(urlMatching("/"))
.willReturn(aResponse()
.withStatus(HttpURLConnection.HTTP_OK)
.withHeader("Content-Type", "application/json")
.withBody(JSON_COPY_EXCEPTION_RESPONSE)));
response = call.callSync(client, new MinionList("minion1"), AUTH).toCompletableFuture().join();
String errorMessage = "ERROR: Could not copy /test1 to /test2";
assertEquals(new JsonPrimitive(errorMessage),
((JsonParsingError) response.get("minion1").error().get()).getJson());
}
@Override
public Instant deserialize ( final JsonElement json, final Type typeOfT, final JsonDeserializationContext context ) throws JsonParseException
{
if ( ! ( json instanceof JsonPrimitive ) )
{
throw new JsonParseException ( "Timestamps should be encoded as JSON strings" );
}
return Instant.from ( this.formatter.parse ( json.getAsString () ) );
}
private static JsonArray setToArray(Set<String> set) {
JsonArray array = new JsonArray();
for (String item : set)
if (!item.isEmpty())
array.add(new JsonPrimitive(item));
return array;
}
@Test
public void testHandleRequest(){
BentenMessage bentenMessage;
JsonElement boardName = new JsonPrimitive("Combined_Services_Team_view");
JsonElement noOfSprints = new JsonPrimitive("1");
bentenMessage =
MessageBuilder.constructBentenSprintMessage(boardName,noOfSprints);
BentenHandlerResponse bentenHandlerResponse =
jiraSprintVelocityActionHandler.handle(bentenMessage);
Assert.assertNotNull(bentenHandlerResponse.getBentenHtmlResponse());
}
public void testCustomNestedSerializers() {
Gson gson = new GsonBuilder().registerTypeAdapter(
BagOfPrimitives.class, new JsonSerializer<BagOfPrimitives>() {
@Override public JsonElement serialize(BagOfPrimitives src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(6);
}
}).create();
ClassWithCustomTypeConverter target = new ClassWithCustomTypeConverter();
assertEquals("{\"bag\":6,\"value\":10}", gson.toJson(target));
}
@Query
public Place getPlace(@Key("text") String text) throws InterruptedException, ExecutionException, TimeoutException {
JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL, "q", "select * from geo.places where text='" + text + "'");
JsonPrimitive jsonObj = jsonObject.getAsJsonObject("query").getAsJsonObject("results").getAsJsonObject("place")
.getAsJsonPrimitive("woeid");
return new Place(text, jsonObj.getAsString());
}
@Test
public void shouldAddGteAndLtFieldToQuery() throws Exception {
// given
// when
NumberRangeQueryBuilder rangeQueryBuilder = new NumberRangeQueryBuilder("someField").gte(100).lt(200);
//then
JsonObject fieldObject = new JsonObject();
fieldObject.add("gte", new JsonPrimitive(100));
fieldObject.add("lt", new JsonPrimitive(200));
assertThat(rangeQueryBuilder.build(), is(object("range", object("someField", fieldObject))));
}
@Test
public void shouldBuildMustNotBoolQuery() throws Exception {
// given
// when
testee.mustNot(new TermQueryBuilder("someName", new JsonPrimitive("someValue")).build());
//then
assertThat(testee.build(), is(
object("bool",
object("must_not",
object("term",
object("someName", "someValue"))))));
}
/**
* Method deserialize.
* @param json JsonElement
* @param typeOfT Type
* @param context JsonDeserializationContext
* @return E
* @throws JsonParseException
* @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)
*/
public E deserialize(
JsonElement json,
Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
checkArgument(json.isJsonPrimitive());
JsonPrimitive jp = json.getAsJsonPrimitive();
checkArgument(jp.isString());
return des.convert(jp.getAsString());
}
public Map<String,Object>loadParasFromJsonString(String str,boolean isPrimitive){
Map<String,Object> params =null;
Gson gson = new Gson();
Type paraMap;
if(isPrimitive){
paraMap= new TypeToken<Map<String, JsonPrimitive>>(){}.getType();
}else{
paraMap= new TypeToken<Map<String, JsonArray>>(){}.getType();
}
params = gson.fromJson(str,paraMap);
return params;
}
private JsonElement serialize(Object value, JsonSerializationContext context) {
if (value instanceof ImmutableSet) {
JsonArray array = new JsonArray();
for (Object element : ((ImmutableSet<?>) value)) {
array.add(serialize(element, context));
}
return array;
} else if (value instanceof Path || value instanceof Pattern) {
return new JsonPrimitive(value.toString());
}
return context.serialize(value);
}
/**
* Updates the JsonObject to have an id property
*
* @param json the element to evaluate
*/
protected void updateIdProperty(final JsonObject json) throws IllegalArgumentException {
for (Entry<String, JsonElement> entry : json.entrySet()) {
String key = entry.getKey();
if (key.equalsIgnoreCase("id")) {
JsonElement element = entry.getValue();
if (isValidTypeId(element)) {
if (!key.equals("id")) {
// force the id name to 'id', no matter the casing
json.remove(key);
// Create a new id property using the given property
// name
JsonPrimitive value = entry.getValue().getAsJsonPrimitive();
if (value.isNumber()) {
json.addProperty("id", value.getAsLong());
} else {
json.addProperty("id", value.getAsString());
}
}
return;
} else {
throw new IllegalArgumentException("The id must be numeric or string");
}
}
}
}
private void modifyUserListChildren(JsonArray children) {
for(int i = 0 ; i < children.size() ; i++){
JsonElement child = children.get(i);
if(child.isJsonObject()){
JsonObject obj = new JsonObject();
obj.add(KIND, new JsonPrimitive(RedditType.User.toString()));
obj.add(DATA, child);
children.set(i, obj);
}
}
}