com.google.gson.JsonElement类的使用及代码示例

x33g5p2x  于2022-01-21 转载在 其他  
字(10.8k)|赞(0)|评价(0)|浏览(320)

本文整理了Java中com.google.gson.JsonElement类的一些代码示例,展示了JsonElement类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。JsonElement类的具体详情如下:
包路径:com.google.gson.JsonElement
类名称:JsonElement

JsonElement介绍

[英]A class representing an element of Json. It could either be a JsonObject, a JsonArray, a JsonPrimitive or a JsonNull.
[中]表示Json元素的类。它可以是JsonObject、JsonArray、JsonPrimitive或JsonNull。

代码示例

代码示例来源:origin: Vedenin/useful-java-links

/**
 *  Example to readJson using TreeModel
 */
private static void readJson() throws IOException {
  JsonParser parser = new JsonParser();
  JsonElement jsonElement = parser.parse("{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}");
  JsonObject rootObject = jsonElement.getAsJsonObject();
  String message = rootObject.get("message").getAsString(); // get property "message"
  JsonObject childObject = rootObject.getAsJsonObject("place"); // get place object
  String place = childObject.get("name").getAsString(); // get property "name"
  System.out.println(message + " " + place); // print "Hi World!"*/
}

代码示例来源:origin: aa112901/remusic

@Override
  public void run() {
    JsonArray jsonArray = HttpUtil.getResposeJsonObject(BMA.Song.songInfo(id).trim()).get("songurl")
        .getAsJsonObject().get("url").getAsJsonArray();
    int len = jsonArray.size();
    int downloadBit = 128;
    for (int i = len - 1; i > -1; i--) {
      int bit = Integer.parseInt(jsonArray.get(i).getAsJsonObject().get("file_bitrate").toString());
      if (bit == downloadBit) {
        musicFileDownInfo = MainApplication.gsonInstance().fromJson(jsonArray.get(i), MusicFileDownInfo.class);
      } else if (bit < downloadBit && bit >= 64) {
        musicFileDownInfo = MainApplication.gsonInstance().fromJson(jsonArray.get(i), MusicFileDownInfo.class);
      }
    }
  }
}

代码示例来源:origin: chanjarster/weixin-java-tools

@Override
public int invite(String userId, String inviteTips) throws WxErrorException {
 String url = "https://qyapi.weixin.qq.com/cgi-bin/invite/send";
 JsonObject jsonObject = new JsonObject();
 jsonObject.addProperty("userid", userId);
 if (StringUtils.isNotEmpty(inviteTips)) {
  jsonObject.addProperty("invite_tips", inviteTips);
 }
 String responseContent = post(url, jsonObject.toString());
 JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
 return tmpJsonElement.getAsJsonObject().get("type").getAsInt();
}

代码示例来源:origin: MovingBlocks/Terasology

@Override
  public Quat4f deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonArray()) {
      JsonArray array = json.getAsJsonArray();
      if (array.size() == 4) {
        return new Quat4f(array.get(0).getAsFloat(), array.get(1).getAsFloat(), array.get(2).getAsFloat(), array.get(3).getAsFloat());
      }
    }
    return null;
  }
}

代码示例来源:origin: MovingBlocks/Terasology

@Override
  public Vector2i deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    JsonArray jsonArray = json.getAsJsonArray();
    return new Vector2i(jsonArray.get(0).getAsInt(), jsonArray.get(1).getAsInt());
  }
}

代码示例来源:origin: chanjarster/weixin-java-tools

@Override
public List<WxCpTag> tagGet() throws WxErrorException {
 String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/list";
 String responseContent = get(url, null);
 JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
 return WxCpGsonBuilder.INSTANCE.create()
   .fromJson(
     tmpJsonElement.getAsJsonObject().get("taglist"),
     new TypeToken<List<WxCpTag>>() {
     }.getType()
   );
}

代码示例来源:origin: iSoron/uhabits

@NonNull
public Command parse(@NonNull String json)
  JsonObject parsed = new JsonParser().parse(json).getAsJsonObject();
  String event = parsed.get("event").getAsString();
  Gson gson = new GsonBuilder().create();
    .fromJson(json, ArchiveHabitsCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, ChangeHabitColorCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, CreateHabitCommand.Record.class)
    .toCommand(modelFactory, habitList);

代码示例来源:origin: chanjarster/weixin-java-tools

@Override
public List<WxMpUserSummary> getUserSummary(Date beginDate, Date endDate) throws WxErrorException {
 String url = "https://api.weixin.qq.com/datacube/getusersummary";
 JsonObject param = new JsonObject();
 param.addProperty("begin_date", SIMPLE_DATE_FORMAT.format(beginDate));
 param.addProperty("end_date", SIMPLE_DATE_FORMAT.format(endDate));
 String responseContent = post(url, param.toString());
 JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
 return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"),
   new TypeToken<List<WxMpUserSummary>>() {
   }.getType());
}

代码示例来源:origin: googleapis/google-cloud-java

/**
  * Update the checksums of the downloaded components. This will avoid the need to download them in
  * the future.
  */
 private void writeLocalChecksums(List<Component> components) throws IOException {
  JsonObject results = new JsonObject();

  try {
   JsonParser parser = new JsonParser();
   try (FileReader reader = new FileReader(getChecksumFile())) {
    results = parser.parse(reader).getAsJsonObject();
   }
  } catch (FileNotFoundException e) {
   // ignored
  }

  for (Component component : components) {
   results.add(component.getId(), new JsonPrimitive(component.getChecksum()));
  }

  try (Writer writer = new FileWriter(getChecksumFile())) {
   new Gson().toJson(results, writer);
  }
 }
}

代码示例来源:origin: xinghongfei/LookLook

List<NewsBean> beans = new ArrayList<NewsBean>();
try {
  JsonParser parser = new JsonParser();
  JsonObject jsonObj = parser.parse(res).getAsJsonObject();
  JsonElement jsonElement = jsonObj.get(value);
  if(jsonElement == null) {
    return null;
  JsonArray jsonArray = jsonElement.getAsJsonArray();
  for (int i = 1; i < jsonArray.size(); i++) {
    JsonObject jo = jsonArray.get(i).getAsJsonObject();
    if (jo.has("skipType") && "special".equals(jo.get("skipType").getAsString())) {
      continue;

代码示例来源:origin: bwssytems/ha-bridge

public List<HomeWizardSmartPlugDevice> getDevices() 
{
  List<HomeWizardSmartPlugDevice> homewizardDevices = new ArrayList<>();	
  try {
    
    String result = requestJson(EMPTY_STRING);
    JsonParser parser = new JsonParser();
    JsonObject resultJson = parser.parse(result).getAsJsonObject();
    cloudPlugId = resultJson.get("id").getAsString();
  
    String all_devices_json = resultJson.get("devices").toString();
    Device[] devices = gson.fromJson(all_devices_json, Device[].class);
    
    // Fix names from JSON
    for (Device device : devices) {
      device.setTypeName(StringUtils.capitalize(device.getTypeName().replace("_", " ")));
      homewizardDevices.add(mapDeviceToHomeWizardSmartPlugDevice(device));
    }
  }
  catch(Exception e) {
    log.warn("Error while get devices from cloud service ", e);
  }
  
  log.info("Found: " + homewizardDevices.size() + " devices");
  return homewizardDevices;
}

代码示例来源:origin: cymcsg/UltimateAndroid

public static ArrayList getArrayListMapFromJson(String jsonString) {
  JsonParser jsonParser = new JsonParser();
  Gson gson = new Gson();
  JsonElement jsonElement = jsonParser.parse(jsonString);
  Logs.d(jsonElement.isJsonArray() + "   " + jsonElement.isJsonObject());
  ArrayList<HashMap<String, Object>> arrayList = new ArrayList<>();
  if (jsonElement.isJsonObject()) {
    arrayList.add(gson.fromJson(jsonElement, HashMap.class));
  } else if (jsonElement.isJsonArray()) {
    arrayList = getListFromJson(jsonString, new TypeToken<ArrayList<HashMap<String, Object>>>() {
    });
  }
  return arrayList;
}

代码示例来源:origin: apache/incubator-gobblin

public static List<ProducerJob> deserialize(String jobs) {
 if (jobs == null || jobs.trim().isEmpty()) {
  jobs = "[]";
 }
 JsonArray jobsJson = new JsonParser().parse(jobs).getAsJsonArray();
 return new Gson().fromJson(jobsJson, new TypeToken<ArrayList<SimpleProducerJob>>() {
 }.getType());
}

代码示例来源:origin: aa112901/remusic

public static MusicDetailInfo getInfo(final String id) {
  MusicDetailInfo info = null;
  try {
    JsonObject jsonObject = HttpUtil.getResposeJsonObject(BMA.Song.songBaseInfo(id).trim()).get("result")
        .getAsJsonObject().get("items").getAsJsonArray().get(0).getAsJsonObject();
    info = MainApplication.gsonInstance().fromJson(jsonObject, MusicDetailInfo.class);
  } catch (Exception e) {
    e.printStackTrace();
  }
  return info;
}

代码示例来源:origin: SonarSource/sonarqube

public static QPMeasureData fromJson(String json) {
 return new QPMeasureData(StreamSupport.stream(new JsonParser().parse(json).getAsJsonArray().spliterator(), false)
  .map(jsonElement -> {
   JsonObject jsonProfile = jsonElement.getAsJsonObject();
   return new QualityProfile(
    jsonProfile.get("key").getAsString(),
    jsonProfile.get("name").getAsString(),
    jsonProfile.get("language").getAsString(),
    UtcDateUtils.parseDateTime(jsonProfile.get("rulesUpdatedAt").getAsString()));
  }).collect(Collectors.toList()));
}

代码示例来源:origin: syncany/syncany

public static Message toMessage(String messageStr) throws Exception {
  String messageType = getMessageType(messageStr);
  Class<? extends Message> messageClass = getMessageClass(messageType);
  JsonObject result = PARSER.parse(messageStr).getAsJsonObject();
  JsonElement serializedMessage = Optional.fromNullable(Iterables.get(result.entrySet(), 0).getValue()).or(new JsonObject());
  Message message = SERIALIZER.fromJson(serializedMessage, messageClass);
  logger.log(Level.INFO, "Message created: " + message);
  return message;
}

代码示例来源:origin: gocd/gocd

@Test
public void shouldAppendTypeFieldWhenSerializingAntTask()
{
  CRTask value = antTask;
  JsonObject jsonObject = (JsonObject)gson.toJsonTree(value);
  assertThat(jsonObject.get("type").getAsString(), is("ant"));
}
@Test

代码示例来源:origin: chanjarster/weixin-java-tools

@Override
public String[] getCallbackIP() throws WxErrorException {
 String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip";
 String responseContent = get(url, null);
 JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
 JsonArray ipList = tmpJsonElement.getAsJsonObject().get("ip_list").getAsJsonArray();
 String[] ipArray = new String[ipList.size()];
 for (int i = 0; i < ipList.size(); i++) {
  ipArray[i] = ipList.get(i).getAsString();
 }
 return ipArray;
}

代码示例来源:origin: apache/incubator-gobblin

JsonObject jsonBody = new JsonParser().parse(entityStr).getAsJsonObject();
if (!jsonBody.get("hasErrors").getAsBoolean()) {
 return;
JsonArray results = jsonBody.get("results").getAsJsonArray();
for (JsonElement jsonElem : results) {
 JsonObject json = jsonElem.getAsJsonObject();
 int subStatusCode = json.get("statusCode").getAsInt();
 if (subStatusCode < 400) {
  continue;
  JsonElement resultJsonElem = json.get("result");
  Preconditions.checkNotNull(resultJsonElem, "Error response should contain result property");
  JsonObject resultJsonObject = resultJsonElem.getAsJsonArray().get(0).getAsJsonObject();
  if (isDuplicate(resultJsonObject, subStatusCode)) {
   continue;

代码示例来源:origin: searchbox-io/Jest

public void setJsonMap(Map<String, Object> resultMap) {
  String json = gson.toJson(resultMap, Map.class);
  setJsonObject(new JsonParser().parse(json).getAsJsonObject());
}

相关文章