本文整理汇总了Java中com.google.gson.JsonPrimitive类的典型用法代码示例。如果您正苦于以下问题:Java JsonPrimitive类的具体用法?Java JsonPrimitive怎么用?Java JsonPrimitive使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
JsonPrimitive类属于com.google.gson包,在下文中一共展示了JsonPrimitive类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: mergeMapField
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
private void mergeMapField(FieldDescriptor field, JsonElement json, Message.Builder builder)
throws InvalidProtocolBufferException {
if (!(json instanceof JsonObject)) {
throw new InvalidProtocolBufferException("Expect a map object but found: " + json);
}
Descriptor type = field.getMessageType();
FieldDescriptor keyField = type.findFieldByName("key");
FieldDescriptor valueField = type.findFieldByName("value");
if (keyField == null || valueField == null) {
throw new InvalidProtocolBufferException("Invalid map field: " + field.getFullName());
}
JsonObject object = (JsonObject) json;
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
Message.Builder entryBuilder = builder.newBuilderForField(field);
Object key = parseFieldValue(keyField, new JsonPrimitive(entry.getKey()), entryBuilder);
Object value = parseFieldValue(valueField, entry.getValue(), entryBuilder);
if (value == null) {
throw new InvalidProtocolBufferException("Map value cannot be null.");
}
entryBuilder.setField(keyField, key);
entryBuilder.setField(valueField, value);
builder.addRepeatedField(field, entryBuilder.build());
}
}
示例2: interpret
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
@Override
public InterpreterResult interpret(String gremlin, InterpreterContext interpreterContext) {
logger.info("execute gremlin traversal {}", gremlin);
try {
ResultSet results = client.submit(gremlin);
JsonArray array = results.stream()
.map(result -> new JsonPrimitive(results.toString()))
.collect(JsonArray::new, JsonArray::add, JsonArray::addAll);
//TODO extract ResultSet
//Case MessageSerializer
return new InterpreterResult(InterpreterResult.Code.SUCCESS, array.toString());
} catch (RuntimeException e) {
return new InterpreterResult(InterpreterResult.Code.ERROR, e.getMessage());
}
}
示例3: createVOInputTypeNode
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
private static JsonElement createVOInputTypeNode(Class inputType, Type genericType) throws Exception {
// no input maps:
if (isTerminalType(inputType)) {
return new JsonPrimitive(ClassUtils.getSimpleName(inputType));
} else {
boolean isCollection = Collection.class.isAssignableFrom(inputType);
if (isCollection) {
try {
inputType = (Class) ((ParameterizedType) genericType).getActualTypeArguments()[0];
} catch (Exception e) {
inputType = Object.class;
}
}
Collection<Method> fields = AssociationPath.listMethods(inputType, VO_METHOD_TRANSFILTER);
if (isTerminalType(inputType) || fields.size() == 0) {
return markMapCollection(new JsonPrimitive(ClassUtils.getSimpleName(inputType)), null, false, isCollection);
} else {
return markMapCollection(createVONode(fields, true), null, false, isCollection);
}
}
}
示例4: getChartData
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
@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;
}
示例5: getVideoFromTopicInfo
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
private JsonPrimitive getVideoFromTopicInfo(JsonObject origin, String sourceInfoKey, String defaultVideoUrl) {
JsonPrimitive result = null;
if (!obfuscate) {
JsonPrimitive vid = getMapValue(
get(origin, InputJsonKeys.VendorAPISource.Topics.info), sourceInfoKey, null, defaultVideoUrl);
if (vid != null && !vid.getAsString().isEmpty()) {
result = vid;
}
}
return (result == null && defaultVideoUrl != null) ? new JsonPrimitive(defaultVideoUrl) : result;
}
示例6: print
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
@Override
protected void print(ExportHelper helper, EventLookupRpcRequest request, List<EventInterface> events, int eventCookieFlags, EventMeetingSortBy sort, boolean asc) throws IOException {
helper.setup("application/json", reference(), false);
Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(src));
}
})
.setFieldNamingStrategy(new FieldNamingStrategy() {
Pattern iPattern = Pattern.compile("i([A-Z])(.*)");
@Override
public String translateName(Field f) {
Matcher matcher = iPattern.matcher(f.getName());
if (matcher.matches())
return matcher.group(1).toLowerCase() + matcher.group(2);
else
return f.getName();
}
})
.setPrettyPrinting().create();
helper.getWriter().write(gson.toJson(events));
}
示例7: parseValues
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
public static List<KvEntry> parseValues(JsonObject valuesObject) {
List<KvEntry> result = new ArrayList<>();
for (Entry<String, JsonElement> valueEntry : valuesObject.entrySet()) {
JsonElement element = valueEntry.getValue();
if (element.isJsonPrimitive()) {
JsonPrimitive value = element.getAsJsonPrimitive();
if (value.isString()) {
result.add(new StringDataEntry(valueEntry.getKey(), value.getAsString()));
} else if (value.isBoolean()) {
result.add(new BooleanDataEntry(valueEntry.getKey(), value.getAsBoolean()));
} else if (value.isNumber()) {
if (value.getAsString().contains(".")) {
result.add(new DoubleDataEntry(valueEntry.getKey(), value.getAsDouble()));
} else {
result.add(new LongDataEntry(valueEntry.getKey(), value.getAsLong()));
}
} else {
throw new JsonSyntaxException("Can't parse value: " + value);
}
} else {
throw new JsonSyntaxException("Can't parse value: " + element);
}
}
return result;
}
示例8: onEnable
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
/**
* Called on when plugin enables
*/
@Override
public void onEnable()
{
this.worldLoader = new WorldLoader(this, SamaGamesAPI.get().getGameManager().getGameProperties().getGameOption("size", new JsonPrimitive(1000)).getAsInt());
this.api = new SurvivalAPI(this);
try
{
NMSPatcher nmsPatcher = new NMSPatcher(this);
nmsPatcher.patchBiomes();
nmsPatcher.patchPotions();
if (SamaGamesAPI.get().getGameManager().getGameProperties().getGameOption("patch-stackable", new JsonPrimitive(false)).getAsBoolean())
nmsPatcher.patchStackable();
}
catch (Exception e)
{
this.getLogger().log(Level.SEVERE, "Error while patching NMS" , e);
}
this.getCommand("uhc").setExecutor(new CommandUHC());
this.getCommand("nextevent").setExecutor(new CommandNextEvent());
this.startTimer = this.getServer().getScheduler().runTaskTimer(this, this::postInit, 20L, 20L);
}
示例9: keyToString
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
private String keyToString(JsonElement keyElement) {
if (keyElement.isJsonPrimitive()) {
JsonPrimitive primitive = keyElement.getAsJsonPrimitive();
if (primitive.isNumber()) {
return String.valueOf(primitive.getAsNumber());
} else if (primitive.isBoolean()) {
return Boolean.toString(primitive.getAsBoolean());
} else if (primitive.isString()) {
return primitive.getAsString();
} else {
throw new AssertionError();
}
} else if (keyElement.isJsonNull()) {
return "null";
} else {
throw new AssertionError();
}
}
示例10: convert
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
@Override
public JsonPrimitive convert(JsonPrimitive value) {
if (value == null) {
return null;
}
if (value.isNumber()) {
return new JsonPrimitive(String.valueOf(value.getAsInt()));
}
try {
Integer.parseInt(value.getAsString());
// if it parses correctly, it is validated:
return value;
} catch (NumberFormatException ex) {
throw new ConverterException(value, this);
}
}
示例11: save
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
/**
* Save a java object as serialized json.
* @param obj - The object to convert to json.
* @param forceJson - Force this object to be handled as if it was Jsonable.
* @return saved - The saved json.
*/
@SuppressWarnings("unchecked")
public static JsonElement save(Object obj, boolean forceJson) {
JsonData data = new JsonData();
if (obj instanceof Jsonable || forceJson) {
getFields(obj).forEach(f -> {
try {
getHandler(f).saveField(data, f.get(obj), f.getName());
} catch (Exception e) {
e.printStackTrace();
}
});
return data.getJsonObject();
}
Object result = getHandler(obj.getClass()).serialize(obj);
if (result instanceof JsonData)
return ((JsonData) result).getJsonObject();
return result instanceof JsonElement ? (JsonElement) result : ReflectionUtil.construct(JsonPrimitive.class, result);
}
示例12: toJson
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
private static JsonElement toJson(Object value) {
if(value instanceof ConfigurationSection) {
return toJson((ConfigurationSection) value);
} else if(value instanceof Map) {
return toJson((Map) value);
} else if(value instanceof List) {
return toJson((List) value);
} else if(value instanceof String) {
return new JsonPrimitive((String) value);
} else if(value instanceof Character) {
return new JsonPrimitive((Character) value);
} else if(value instanceof Number) {
return new JsonPrimitive((Number) value);
} else if(value instanceof Boolean) {
return new JsonPrimitive((Boolean) value);
} else if(value == null) {
return JsonNull.INSTANCE;
} else {
throw new IllegalArgumentException("Cannot coerce " + value.getClass().getSimpleName() + " to JSON");
}
}
示例13: getRegistrationTags
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
private JsonArray getRegistrationTags() throws IOException {
JsonArray retval = new JsonArray();
String tag = "{\"type\":\"" + getShortServiceName() + "\"}";
retval.add(new JsonPrimitive("t-" + binaryEncode(tag)));
tag = "{\"transport\":\"http\"}";
retval.add(new JsonPrimitive("t-" + binaryEncode(tag)));
tag = "{\"broker\":\"http\"}";
retval.add(new JsonPrimitive("t-" + binaryEncode(tag)));
tag = "{\"server\":\"rpc\"}";
retval.add(new JsonPrimitive("t-" + binaryEncode(tag)));
tag = "{\"registry\":\"consul\"}";
retval.add(new JsonPrimitive("t-" + binaryEncode(tag)));
addEndpointsTags(retval);
tag = getServiceVersion();
retval.add(new JsonPrimitive("v-" + binaryEncode(tag)));
return retval;
}
示例14: update
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
private void update() {
try {
URLConnection conn = new URL(url).openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
String json = "";
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
json = reader.lines().collect(Collectors.joining("\n"));
}
json = json.trim().replaceAll("\\[", "").replaceAll("\\]", ""); //quick and dirty fix
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
JsonPrimitive priceDollars = jsonObject.getAsJsonPrimitive("price_usd");
price = priceDollars.getAsString();
int maxIndex = price.indexOf(".") + 3;
if (price.length() >= maxIndex)
price = price.substring(0, maxIndex);
} catch (Exception e) {
e.printStackTrace();
price = "0.00";
}
price = "{\"price\":\"" + price + "\"}";
}
示例15: setVideoPropertiesInSession
import com.google.gson.JsonPrimitive; //导入依赖的package包/类
private void setVideoPropertiesInSession(JsonObject origin, JsonObject dest) {
boolean isLivestream = isLivestreamed(origin);
set(new JsonPrimitive(isLivestream), dest, OutputJsonKeys.Sessions.isLivestream);
JsonPrimitive vid = null;
if (isLivestream) {
vid = getVideoFromTopicInfo(origin, InputJsonKeys.VendorAPISource.Topics.INFO_STREAM_VIDEO_ID,
Config.VIDEO_LIVESTREAMURL_FOR_EMPTY);
} else {
vid = getMapValue(
get(origin, InputJsonKeys.VendorAPISource.Topics.info), InputJsonKeys.VendorAPISource.Topics.INFO_VIDEO_URL,
Converters.YOUTUBE_URL, null);
}
if (vid != null && !vid.getAsString().isEmpty()) {
set(vid, dest, OutputJsonKeys.Sessions.youtubeUrl);
}
}