Java Code Examples for com.google.gson.JsonArray#iterator()

The following examples show how to use com.google.gson.JsonArray#iterator() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KcaApiData.java    From kcanotify_h5-master with GNU General Public License v3.0 7 votes vote down vote up
public static int updateUserShipData(JsonArray data) {
    Set<Integer> prevItemIds;
    if (userShipData == null) {
        userShipData = new HashMap<Integer, JsonObject>();
        prevItemIds = new HashSet<Integer>();
    } else {
        prevItemIds = new HashSet<Integer>(userShipData.keySet());
    }

    JsonElement temp;
    for (Iterator<JsonElement> itr = data.iterator(); itr.hasNext(); ) {
        temp = itr.next();
        Integer api_id = temp.getAsJsonObject().get("api_id").getAsInt();
        if (!prevItemIds.contains(api_id)) {
            userShipData.put(api_id, temp.getAsJsonObject());
        } else if (!userShipData.get(api_id).equals(temp)) {
            userShipData.put(api_id, temp.getAsJsonObject());
        }
        prevItemIds.remove(api_id);
    }
    for (Integer i : prevItemIds) {
        userShipData.remove(i);
    }
    return userShipData.size();
}
 
Example 2
Source File: AssignedSensors.java    From smarthome with Eclipse Public License 2.0 7 votes vote down vote up
private void init(JsonObject jObject) {
    if (jObject.get(JSONApiResponseKeysEnum.SENSORS.getKey()) != null
            && jObject.get(JSONApiResponseKeysEnum.SENSORS.getKey()).isJsonArray()) {
        JsonArray jArray = jObject.get(JSONApiResponseKeysEnum.SENSORS.getKey()).getAsJsonArray();
        if (jArray.size() != 0) {
            sensors = new LinkedList<AssignSensorType>();
            Iterator<JsonElement> iter = jArray.iterator();
            while (iter.hasNext()) {
                JsonObject assignedSensor = iter.next().getAsJsonObject();
                Short sensorType = null;
                String meterDSUID = null;
                if (assignedSensor.get(JSONApiResponseKeysEnum.SENSOR_TYPE.getKey()) != null) {
                    sensorType = assignedSensor.get(JSONApiResponseKeysEnum.SENSOR_TYPE.getKey()).getAsShort();
                }
                if (assignedSensor.get(JSONApiResponseKeysEnum.DSUID_LOWER_CASE.getKey()) != null) {
                    meterDSUID = assignedSensor.get(JSONApiResponseKeysEnum.DSUID_LOWER_CASE.getKey())
                            .getAsString();
                }
                sensors.add(new AssignSensorType(SensorEnum.getSensor(sensorType), meterDSUID));
            }
        }
    }
}
 
Example 3
Source File: DsAPIImpl.java    From smarthome with Eclipse Public License 2.0 7 votes vote down vote up
@Override
public HashMap<Integer, BaseSensorValues> getApartmentSensorValues(String sessionToken) {
    String response = transport.execute(SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.APARTMENT)
            .addFunction(FunctionKeys.GET_SENSOR_VALUES).addParameter(ParameterKeys.TOKEN, sessionToken)
            .buildRequestString());
    JsonObject responseObj = JSONResponseHandler.toJsonObject(response);

    if (JSONResponseHandler.checkResponse(responseObj)) {
        JsonObject obj = JSONResponseHandler.getResultJsonObject(responseObj);
        if (obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).isJsonArray()) {
            JsonArray jArray = obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).getAsJsonArray();
            WeatherSensorData weather = new WeatherSensorData(obj);
            if (jArray.size() != 0) {
                HashMap<Integer, BaseSensorValues> map = new HashMap<Integer, BaseSensorValues>(jArray.size() + 1);
                Iterator<JsonElement> iter = jArray.iterator();
                while (iter.hasNext()) {
                    SensorValues sensorValues = new SensorValues(iter.next().getAsJsonObject());
                    map.put(sensorValues.getZoneID(), sensorValues);
                }
                map.put(GeneralLibConstance.BROADCAST_ZONE_GROUP_ID, weather);
                return map;
            }
        }
    }
    return null;
}
 
Example 4
Source File: DsAPIImpl.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public List<TemperatureControlStatus> getApartmentTemperatureControlStatus(String sessionToken) {
    String response = transport.execute(SimpleRequestBuilder.buildNewJsonRequest(ClassKeys.APARTMENT)
            .addFunction(FunctionKeys.GET_TEMPERATURE_CONTROL_STATUS)
            .addParameter(ParameterKeys.TOKEN, sessionToken).buildRequestString());
    JsonObject responseObj = JSONResponseHandler.toJsonObject(response);

    if (JSONResponseHandler.checkResponse(responseObj)) {
        JsonObject obj = JSONResponseHandler.getResultJsonObject(responseObj);
        if (obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).isJsonArray()) {
            JsonArray jArray = obj.get(JSONApiResponseKeysEnum.ZONES.getKey()).getAsJsonArray();
            if (jArray.size() != 0) {
                List<TemperatureControlStatus> list = new ArrayList<TemperatureControlStatus>(jArray.size());
                Iterator<JsonElement> iter = jArray.iterator();
                while (iter.hasNext()) {
                    TemperatureControlStatus tContStat = new TemperatureControlStatus(
                            iter.next().getAsJsonObject());
                    list.add(tContStat);
                }
                return list;
            }
        }
    }
    return null;
}
 
Example 5
Source File: SalesforceSource.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Get the row count for a time range
 */
private int getCountForRange(TableCountProbingContext probingContext, StrSubstitutor sub,
    Map<String, String> subValues, long startTime, long endTime) {
  String startTimeStr = Utils.dateToString(new Date(startTime), SalesforceExtractor.SALESFORCE_TIMESTAMP_FORMAT);
  String endTimeStr = Utils.dateToString(new Date(endTime), SalesforceExtractor.SALESFORCE_TIMESTAMP_FORMAT);

  subValues.put("start", startTimeStr);
  subValues.put("end", endTimeStr);

  String query = sub.replace(PROBE_PARTITION_QUERY_TEMPLATE);

  log.debug("Count query: " + query);
  probingContext.probeCount++;

  JsonArray records = getRecordsForQuery(probingContext.connector, query);
  Iterator<JsonElement> elements = records.iterator();
  JsonObject element = elements.next().getAsJsonObject();

  return element.get("cnt").getAsInt();
}
 
Example 6
Source File: MainView.java    From HiJson with Apache License 2.0 6 votes vote down vote up
/**
 * 处理json数组.
 * @param arr
 * @param pNode
 * @param key
 */
private void createJsonArray(JsonArray arr,DefaultMutableTreeNode pNode,String key){
    int index = 0;
    DefaultMutableTreeNode child = Kit.arrNode(key);
    for (Iterator it = arr.iterator(); it.hasNext();) {
        JsonElement el = (JsonElement)it.next();
        if(el.isJsonObject()){
            JsonObject  obj = el.getAsJsonObject();
            DefaultMutableTreeNode node = Kit.objNode(index);
            createJsonObject(obj, node);
            child.add(node);
        }else if(el.isJsonArray()){
            JsonArray lst = el.getAsJsonArray();
            createJsonArray(lst,child,Kit.fkey(index));
        }else if(el.isJsonNull()){
            child.add(Kit.nullNode(index));
        }else if(el.isJsonPrimitive()){
            formatJsonPrimitive(Kit.fkey(index),el.getAsJsonPrimitive(),child);
        }
        ++index;
    }
    pNode.add(child);
}
 
Example 7
Source File: HomeRobot.java    From wakao-app with MIT License 6 votes vote down vote up
private List<ArticleObj> parseJSON2Obj(String json) {
	List<ArticleObj> objs = new ArrayList<ArticleObj>();
	ArticleObj obj = null;
	JsonElement element = new JsonParser().parse(json);
	JsonArray array = element.getAsJsonObject().get("data")
			.getAsJsonArray();
	// 遍历数组
	Iterator<JsonElement> it = array.iterator();
	Gson gson = new Gson();
	while (it.hasNext()) {
		JsonElement e = it.next();
		// JsonElement转换为JavaBean对象
		obj = gson.fromJson(e, ArticleObj.class);
		objs.add(obj);
	}

	return objs;
}
 
Example 8
Source File: BinanceEventDepthLevelUpdate.java    From java-binance-api with MIT License 6 votes vote down vote up
public BinanceEventDepthLevelUpdate(JsonObject event){
    this.lastUpdateId = event.get("lastUpdateId").getAsLong();
    this.bids = new LinkedList();
    JsonArray b = event.get("bids").getAsJsonArray();
    Iterator var3 = b.iterator();

    while(var3.hasNext()) {
        JsonElement bidElement = (JsonElement)var3.next();
        this.bids.add(new BinanceBidOrAsk(BinanceBidType.BID, bidElement.getAsJsonArray()));
    }

    this.asks = new LinkedList();
    JsonArray a = event.get("asks").getAsJsonArray();
    Iterator var7 = a.iterator();

    while(var7.hasNext()) {
        JsonElement askElement = (JsonElement)var7.next();
        this.asks.add(new BinanceBidOrAsk(BinanceBidType.ASK, askElement.getAsJsonArray()));
    }
}
 
Example 9
Source File: OpenViduClient.java    From openvidu with Apache License 2.0 5 votes vote down vote up
public Map<String, List<String>> joinRoom(String roomName, String userName)
    throws IOException {
      
  JsonObject params = new JsonObject();
  params.addProperty(JOINROOM_ROOM_PARAM, roomName);
  params.addProperty(JOINROOM_USER_PARAM, userName);

  JsonElement result = client.sendRequest(JOINROOM_METHOD, params);
  Map<String, List<String>> peers = new HashMap<String, List<String>>();
  JsonArray jsonPeers = JsonRoomUtils.getResponseProperty(result, "value", JsonArray.class);
  if (jsonPeers.size() > 0) {
    Iterator<JsonElement> peerIt = jsonPeers.iterator();
    while (peerIt.hasNext()) {
      JsonElement peer = peerIt.next();
      String peerId = JsonRoomUtils.getResponseProperty(peer, JOINROOM_PEERID_PARAM,
          String.class);
      List<String> streams = new ArrayList<String>();
      JsonArray jsonStreams = JsonRoomUtils.getResponseProperty(peer, JOINROOM_PEERSTREAMS_PARAM,
          JsonArray.class, true);
      if (jsonStreams != null) {
        Iterator<JsonElement> streamIt = jsonStreams.iterator();
        while (streamIt.hasNext()) {
          streams.add(JsonRoomUtils.getResponseProperty(streamIt.next(),
              JOINROOM_PEERSTREAMID_PARAM, String.class));
        }
      }
      peers.put(peerId, streams);
    }
  }
  return peers;
}
 
Example 10
Source File: JsonUtil.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
public static int find(JsonElement element, JsonArray array, Set<Integer> exclude, String... fields) {
	if (array == null || array.size() == 0)
		return -1;
	if (element == null)
		return -1;
	if (element.isJsonPrimitive())
		return findPrimitive(element.getAsJsonPrimitive(), array);
	if (fields == null)
		return -1;
	if (!element.isJsonObject())
		return -1;
	JsonObject object = element.getAsJsonObject();
	String[] values = getValues(object, fields);
	if (values == null)
		return -1;
	Iterator<JsonElement> iterator = array.iterator();
	int index = 0;
	while (iterator.hasNext()) {
		JsonElement other = iterator.next();
		if (!other.isJsonObject()) {
			index++;
			continue;
		}
		String[] otherValues = getValues(other.getAsJsonObject(), fields);
		if (equal(values, otherValues) && (exclude == null || !exclude.contains(index)))
			return index;
		index++;
	}
	return -1;
}
 
Example 11
Source File: FlutterWidgetPropertyEditor.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<FlutterWidgetPropertyEditor> fromJsonArray(JsonArray jsonArray) {
  if (jsonArray == null) {
    return EMPTY_LIST;
  }
  ArrayList<FlutterWidgetPropertyEditor> list = new ArrayList<FlutterWidgetPropertyEditor>(jsonArray.size());
  Iterator<JsonElement> iterator = jsonArray.iterator();
  while (iterator.hasNext()) {
    list.add(fromJson(iterator.next().getAsJsonObject()));
  }
  return list;
}
 
Example 12
Source File: ExtractWidgetFeedback.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<ExtractWidgetFeedback> fromJsonArray(JsonArray jsonArray) {
  if (jsonArray == null) {
    return EMPTY_LIST;
  }
  ArrayList<ExtractWidgetFeedback> list = new ArrayList<ExtractWidgetFeedback>(jsonArray.size());
  Iterator<JsonElement> iterator = jsonArray.iterator();
  while (iterator.hasNext()) {
    list.add(fromJson(iterator.next().getAsJsonObject()));
  }
  return list;
}
 
Example 13
Source File: ExtractWidgetOptions.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<ExtractWidgetOptions> fromJsonArray(JsonArray jsonArray) {
  if (jsonArray == null) {
    return EMPTY_LIST;
  }
  ArrayList<ExtractWidgetOptions> list = new ArrayList<ExtractWidgetOptions>(jsonArray.size());
  Iterator<JsonElement> iterator = jsonArray.iterator();
  while (iterator.hasNext()) {
    list.add(fromJson(iterator.next().getAsJsonObject()));
  }
  return list;
}
 
Example 14
Source File: GsonDeserializationUtils.java    From nd4j with Apache License 2.0 5 votes vote down vote up
private static void getSizeMultiDimensionalArray(JsonArray jsonArray, List<Integer> dimensions) {
    Iterator<JsonElement> iterator = jsonArray.iterator();

    if (iterator.hasNext()) {
        JsonElement jsonElement = iterator.next();
        if (jsonElement.isJsonArray()) {
            JsonArray shapeArray = jsonElement.getAsJsonArray();
            dimensions.add(shapeArray.size());
            getSizeMultiDimensionalArray(shapeArray, dimensions);
        }
    }
}
 
Example 15
Source File: SaveStockDataFromSina.java    From SaveStockData with Apache License 2.0 5 votes vote down vote up
private static <T> ArrayList<T> JSONArrayStringToArrayList(String jsonString,Class<T> classofT){
	Gson gson=new Gson();
	JsonParser parser = new JsonParser();
	JsonElement el = parser.parse(jsonString);
	JsonArray jsonArray=el.getAsJsonArray();
	Iterator<JsonElement> it = jsonArray.iterator();
	ArrayList<T> al=new ArrayList<>();
	while(it.hasNext()){
		JsonElement e = it.next();
		T data=gson.fromJson(e, classofT);
		al.add(data);
	}
	return al;
}
 
Example 16
Source File: WeatherSource.java    From yql-plus with Apache License 2.0 5 votes vote down vote up
@Query
public List<Forecast> getForecast(@Key("woeid") String woeid, @Key("u") String u) throws InterruptedException, ExecutionException, TimeoutException, UnsupportedEncodingException {
    JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL.replace("{woeid}", woeid).replace("{u}", u));
    JsonArray jsonArray = (JsonArray)jsonObject.getAsJsonObject("query").getAsJsonObject("results").getAsJsonObject("channel").getAsJsonObject("item").get("forecast");
    Iterator<JsonElement> it = jsonArray.iterator();
    List<Forecast> forecasts = Lists.newArrayList();
    while(it.hasNext()) {
        JsonElement ele = it.next();
        ForecastBase tmp = HttpUtil.getGson().fromJson(ele.toString(), ForecastBase.class);
        forecasts.add(new Forecast(tmp.getCode(),  tmp.getDate(), tmp.getDay(), tmp.getHigh(),
                tmp.getLow(), tmp.getText(), woeid, u));
    }
    return forecasts;
}
 
Example 17
Source File: SirenService.java    From estatio with Apache License 2.0 5 votes vote down vote up
private List<SirenResult> getSirenResultsFromJsonArray(JsonArray jsonArray) {
    Set<SirenResult> resultsSet = new TreeSet<>();
    Iterator<JsonElement> recordsIterator = jsonArray.iterator();

    recordsIterator.forEachRemaining(record -> {
        try {
            SirenResult result = jsonObjectToSirenResult(record.getAsJsonObject());
            resultsSet.add(result);
        } catch (Exception e) {
            // ignore
        }
    });

    return Lists.newArrayList(resultsSet);
}
 
Example 18
Source File: FlutterWidgetProperty.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<FlutterWidgetProperty> fromJsonArray(JsonArray jsonArray) {
  if (jsonArray == null) {
    return EMPTY_LIST;
  }
  ArrayList<FlutterWidgetProperty> list = new ArrayList<FlutterWidgetProperty>(jsonArray.size());
  Iterator<JsonElement> iterator = jsonArray.iterator();
  while (iterator.hasNext()) {
    list.add(fromJson(iterator.next().getAsJsonObject()));
  }
  return list;
}
 
Example 19
Source File: FlutterWidgetPropertyValue.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<FlutterWidgetPropertyValue> fromJsonArray(JsonArray jsonArray) {
  if (jsonArray == null) {
    return EMPTY_LIST;
  }
  ArrayList<FlutterWidgetPropertyValue> list = new ArrayList<FlutterWidgetPropertyValue>(jsonArray.size());
  Iterator<JsonElement> iterator = jsonArray.iterator();
  while (iterator.hasNext()) {
    list.add(fromJson(iterator.next().getAsJsonObject()));
  }
  return list;
}
 
Example 20
Source File: FlutterWidgetPropertyValueEnumItem.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static List<FlutterWidgetPropertyValueEnumItem> fromJsonArray(JsonArray jsonArray) {
  if (jsonArray == null) {
    return EMPTY_LIST;
  }
  ArrayList<FlutterWidgetPropertyValueEnumItem> list = new ArrayList<FlutterWidgetPropertyValueEnumItem>(jsonArray.size());
  Iterator<JsonElement> iterator = jsonArray.iterator();
  while (iterator.hasNext()) {
    list.add(fromJson(iterator.next().getAsJsonObject()));
  }
  return list;
}