當前位置: 首頁>>代碼示例>>Java>>正文


Java JsonPrimitive類代碼示例

本文整理匯總了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());
  }
}
 
開發者ID:SeldonIO,項目名稱:seldon-core,代碼行數:25,代碼來源:JsonFormat.java

示例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());
    }
}
 
開發者ID:shikeio,項目名稱:gremzeppelin,代碼行數:18,代碼來源:GremlinInterpreter.java

示例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);
		}
	}
}
 
開發者ID:phoenixctms,項目名稱:ctsms,代碼行數:22,代碼來源:IndexResource.java

示例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;
}
 
開發者ID:codeHusky,項目名稱:HuskyUI-Plugin,代碼行數:18,代碼來源:Metrics.java

示例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;
}
 
開發者ID:dreaminglion,項目名稱:iosched-reader,代碼行數:13,代碼來源:DataExtractor.java

示例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));
}
 
開發者ID:Jenner4S,項目名稱:unitimes,代碼行數:26,代碼來源:EventsExportEventsToJSON.java

示例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;
}
 
開發者ID:osswangxining,項目名稱:iotplatform,代碼行數:26,代碼來源:JsonConverter.java

示例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);
}
 
開發者ID:SamaGames,項目名稱:SurvivalAPI,代碼行數:29,代碼來源:SurvivalPlugin.java

示例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();
  }
}
 
開發者ID:odoo-mobile-intern,項目名稱:odoo-work,代碼行數:19,代碼來源:MapTypeAdapterFactory.java

示例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);
  }
}
 
開發者ID:dreaminglion,項目名稱:iosched-reader,代碼行數:17,代碼來源:IntegerToStringConverter.java

示例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);
}
 
開發者ID:Kneesnap,項目名稱:Kineticraft,代碼行數:28,代碼來源:JsonSerializer.java

示例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");
    }
}
 
開發者ID:OvercastNetwork,項目名稱:ProjectAres,代碼行數:22,代碼來源:ConfigUtils.java

示例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;
}
 
開發者ID:Sixt,項目名稱:ja-micro,代碼行數:18,代碼來源:RegistrationManager.java

示例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 + "\"}";
}
 
開發者ID:thehen101,項目名稱:RainServer,代碼行數:26,代碼來源:CommandPrice.java

示例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);
  }
}
 
開發者ID:dreaminglion,項目名稱:iosched-reader,代碼行數:19,代碼來源:DataExtractor.java


注:本文中的com.google.gson.JsonPrimitive類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。