Java Code Examples for org.json.JSONArray#optJSONArray()

The following examples show how to use org.json.JSONArray#optJSONArray() . 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: TagDeserializer.java    From Klyph with MIT License 6 votes vote down vote up
public Map<String, List<Tag>> deserializeMap(JSONArray data)
{
	Map<String, List<Tag>> map = new Hashtable<String, List<Tag>>();

	if (data != null)
	{
		int n = data.length();
		for (int i = 0; i < n; i++)
		{
			JSONArray tags = data.optJSONArray(i);
			map.put(String.valueOf(i), deserializeArray(tags, Tag.class));

		}
	}

	return map;
}
 
Example 2
Source File: TagDeserializer.java    From KlyphMessenger with MIT License 6 votes vote down vote up
public Map<String, List<Tag>> deserializeMap(JSONArray data)
{
	Map<String, List<Tag>> map = new Hashtable<String, List<Tag>>();

	if (data != null)
	{
		int n = data.length();
		for (int i = 0; i < n; i++)
		{
			JSONArray tags = data.optJSONArray(i);
			map.put(String.valueOf(i), deserializeArray(tags, Tag.class));

		}
	}

	return map;
}
 
Example 3
Source File: TagDeserializer.java    From KlyphMessenger with MIT License 6 votes vote down vote up
public Map<String, List<Tag>> deserializeMap(JSONArray data)
{
	Map<String, List<Tag>> map = new Hashtable<String, List<Tag>>();

	if (data != null)
	{
		int n = data.length();
		for (int i = 0; i < n; i++)
		{
			JSONArray tags = data.optJSONArray(i);
			map.put(String.valueOf(i), deserializeArray(tags, Tag.class));

		}
	}

	return map;
}
 
Example 4
Source File: TagDeserializer.java    From Klyph with MIT License 6 votes vote down vote up
public Map<String, List<Tag>> deserializeMap(JSONArray data)
{
	Map<String, List<Tag>> map = new Hashtable<String, List<Tag>>();

	if (data != null)
	{
		int n = data.length();
		for (int i = 0; i < n; i++)
		{
			JSONArray tags = data.optJSONArray(i);
			map.put(String.valueOf(i), deserializeArray(tags, Tag.class));

		}
	}

	return map;
}
 
Example 5
Source File: SerializerTest.java    From firebase-android-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeArray() throws JSONException {
  List<Object> input = Arrays.asList(1, "two", Arrays.asList(3, 4));

  Serializer serializer = new Serializer();
  Object result = serializer.encode(input);
  assertTrue(result instanceof JSONArray);
  JSONArray actual = (JSONArray) result;

  assertEquals(3, actual.length());
  assertEquals(1, actual.opt(0));
  assertEquals("two", actual.opt(1));
  assertTrue(actual.opt(2) instanceof JSONArray);
  JSONArray third = actual.optJSONArray(2);
  assertEquals(2, third.length());
  assertEquals(3, third.opt(0));
  assertEquals(4, third.opt(1));
}
 
Example 6
Source File: GeoJsonExtent.java    From ground-android with Apache License 2.0 6 votes vote down vote up
private ImmutableList<LatLng> ringCoordinatesToLatLngs(JSONArray exteriorRing) {
  if (exteriorRing == null) {
    return ImmutableList.of();
  }

  List<LatLng> coordinates = new ArrayList<>();

  for (int i = 0; i < exteriorRing.length(); i++) {
    JSONArray point = exteriorRing.optJSONArray(i);
    double lat = point.optDouble(1, 0.0);
    double lng = point.optDouble(0, 0.0);

    // PMD complains about instantiating objects in loops, but here, we retain a reference to the
    // object after the loop exits--the PMD recommendation here makes little sense, and is
    // presumably intended to prevent short-lived allocations.
    coordinates.add(new LatLng(lat, lng)); // NOPMD
  }

  return stream(coordinates).collect(toImmutableList());
}
 
Example 7
Source File: SimpleBitfinexApiBroker.java    From bitfinex-v2-wss-api-java with Apache License 2.0 5 votes vote down vote up
/**
 * Handle a channel callback
 * @param message
 */
private void handleChannelCallback(final String message) {
	// Channel callback
	updateConnectionHeartbeat();

	// JSON callback
	final JSONArray jsonArray = new JSONArray(new JSONTokener(message));

	if(connectionFeatureManager.isConnectionFeatureActive(BitfinexConnectionFeature.SEQ_ALL)) {
		sequenceNumberAuditor.auditPackage(jsonArray);
	}

	final int channel = jsonArray.getInt(0);
	final ChannelCallbackHandler channelCallbackHandler = channelIdToHandlerMap.get(channel);
	if (channelCallbackHandler == null) {
		logger.error("Unable to determine symbol for channel {} / data is {} ", channel, jsonArray);
		reconnect();
		return;
	}
	String action = null;
	final JSONArray payload;
	if (jsonArray.get(1) instanceof String) {
		action = jsonArray.getString(1);
		payload = jsonArray.optJSONArray(2);
	} else {
		payload = jsonArray.optJSONArray(1);
	}
	if (Objects.equals(action, "hb")) {
		quoteManager.updateChannelHeartbeat(channelCallbackHandler.getSymbol());
	}
	try {
		if (payload == null) {
			return;
		}
		channelCallbackHandler.handleChannelData(action, payload);
	} catch (final BitfinexClientException e) {
		logger.error("Got exception while handling callback", e);
	}
}
 
Example 8
Source File: NotificationHandler.java    From bitfinex-v2-wss-api-java with Apache License 2.0 5 votes vote down vote up
private BitfinexSubmittedOrder jsonToBitfinexSubmittedOrder(JSONArray array) {
    final JSONArray orderJson = array.optJSONArray(4);
    final long oid = orderJson.optLong(0, -1);
    final long gid = orderJson.optLong(1, -1);
    final long cid = orderJson.optLong(2, -1);
    final String symbol = orderJson.optString(3);
    final String stateValue = array.optString(7);
    final String state = array.optString(6);

    final BitfinexSubmittedOrder submittedOrder = new BitfinexSubmittedOrder();
    if (oid != -1) {
        submittedOrder.setOrderId(oid);
    }
    if (gid != -1) {
        submittedOrder.setClientGroupId(gid);
    }
    if( cid != -1) {
        submittedOrder.setClientId(cid);
    }

    if (!Strings.isNullOrEmpty(stateValue)) {
        submittedOrder.setStatusDescription(stateValue);
    }

    if (!Strings.isNullOrEmpty(symbol)) {
        submittedOrder.setCurrencyPair(BitfinexCurrencyPair.fromSymbolString(symbol));
    }
    submittedOrder.setStatus(BitfinexSubmittedOrderStatus.ERROR);
    logger.error("State for order {} is {}, reason is {}", submittedOrder.getOrderId(), state, stateValue);
    return submittedOrder;
}
 
Example 9
Source File: Zhihu.java    From catnut with MIT License 5 votes vote down vote up
@Override
public ContentValues convert(JSONArray array) {
	long now = System.currentTimeMillis();

	ContentValues item = new ContentValues();

	// 用当前时间戳来作为item在本地的标识与排序,降序,时间戳越大代表越新
	item.put(BaseColumns._ID, now);

	// 答案相关
	item.put(STATUS, array.optString(1));
	item.put(ANSWER, array.optString(2));
	item.put(LAST_ALTER_DATE, array.optLong(4) * 1000);
	item.put(ANSWER_ID, array.optLong(5));

	// 答主相关
	JSONArray user = array.optJSONArray(6);
	if (user != null) {
		item.put(NICK, user.optString(0));
		item.put(UID, user.optString(1));
		item.put(AVATAR, user.optInt(2));
	}

	// 问题相关
	JSONArray question = array.optJSONArray(7);
	if (question != null) {
		item.put(TITLE, question.optString(1, null));
		item.put(DESCRIPTION, question.optString(2));
		item.put(QUESTION_ID, question.optLong(3));
	}

	return item;
}
 
Example 10
Source File: Polygon.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void setRings(JSONArray rings) {
    this.mRings.clear();
    if (rings != null) {
        for (int i = 0; i < rings.length(); i++) {
            JSONArray ringJSON = rings.optJSONArray(i);
            if (ringJSON != null) {
                this.mRings.add(new Ring(ringJSON));
            }
        }
    }
}
 
Example 11
Source File: MultiLineString.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void setLineStrings(JSONArray lineStrings) {
    this.mLineStrings.clear();
    if (lineStrings != null) {
        for (int i = 0; i < lineStrings.length(); i++) {
            JSONArray lineJSON = lineStrings.optJSONArray(i);
            if (lineJSON != null) {
                this.mLineStrings.add(new LineString(lineJSON));
            }
        }
    }
}
 
Example 12
Source File: PositionList.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void setPositions(JSONArray positions) {
    this.mPositions.clear();
    if (positions != null) {
        for (int i = 0; i < positions.length(); i++) {
            JSONArray position = positions.optJSONArray(i);
            if (position != null) {
                this.mPositions.add(new Position(position));
            }
        }
    }
}
 
Example 13
Source File: MultiPolygon.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void setPolygons(JSONArray polygons) {
    this.mPolygons.clear();
    if (polygons != null) {
        for (int i = 0; i < polygons.length(); i++) {
            JSONArray polyJSON = polygons.optJSONArray(i);
            if (polyJSON != null) {
                this.mPolygons.add(new Polygon(polyJSON));
            }
        }
    }
}
 
Example 14
Source File: ShapeData.java    From atlas with Apache License 2.0 5 votes vote down vote up
private static PointF vertexAtIndex(int idx, JSONArray points) {
  if (idx >= points.length()) {
    throw new IllegalArgumentException(
        "Invalid index " + idx + ". There are only " + points.length() + " points.");
  }

  JSONArray pointArray = points.optJSONArray(idx);
  Object x = pointArray.opt(0);
  Object y = pointArray.opt(1);
  return new PointF(
      x instanceof Double ? new Float((Double) x) : (int) x,
      y instanceof Double ? new Float((Double) y) : (int) y);
}
 
Example 15
Source File: CommonParser.java    From letv with Apache License 2.0 4 votes vote down vote up
protected JSONArray getJSONArray(JSONArray array, int index) {
    return array.optJSONArray(index);
}
 
Example 16
Source File: JSONArrayTest.java    From JSON-Java-unit-test with Apache License 2.0 4 votes vote down vote up
/**
 * Create a JSONArray doc with a variety of different elements.
 * Confirm that the values can be accessed via the opt[type](index)
 * and opt[type](index, default) API methods.
 */
@SuppressWarnings("boxing")
@Test 
public void opt() {
    JSONArray jsonArray = new JSONArray(this.arrayStr);
    assertTrue("Array opt value true",
            Boolean.TRUE == jsonArray.opt(0));
    assertTrue("Array opt value out of range",
            null == jsonArray.opt(-1));

    assertTrue("Array opt value out of range",
            null == jsonArray.opt(jsonArray.length()));

     assertTrue("Array opt boolean",
            Boolean.TRUE == jsonArray.optBoolean(0));
    assertTrue("Array opt boolean default",
            Boolean.FALSE == jsonArray.optBoolean(-1, Boolean.FALSE));
    assertTrue("Array opt boolean implicit default",
            Boolean.FALSE == jsonArray.optBoolean(-1));

    assertTrue("Array opt double",
            new Double(23.45e-4).equals(jsonArray.optDouble(5)));
    assertTrue("Array opt double default",
            new Double(1).equals(jsonArray.optDouble(0, 1)));
    assertTrue("Array opt double default implicit",
       new Double(jsonArray.optDouble(99)).isNaN());

    assertTrue("Array opt float",
            new Float(23.45e-4).equals(jsonArray.optFloat(5)));
    assertTrue("Array opt float default",
            new Float(1).equals(jsonArray.optFloat(0, 1)));
    assertTrue("Array opt float default implicit",
       new Float(jsonArray.optFloat(99)).isNaN());

    assertTrue("Array opt Number",
            new Double(23.45e-4).equals(jsonArray.optNumber(5)));
    assertTrue("Array opt Number default",
            new Double(1).equals(jsonArray.optNumber(0, 1d)));
    assertTrue("Array opt Number default implicit",
       new Double(jsonArray.optNumber(99,Double.NaN).doubleValue()).isNaN());

    assertTrue("Array opt int",
            new Integer(42).equals(jsonArray.optInt(7)));
    assertTrue("Array opt int default",
            new Integer(-1).equals(jsonArray.optInt(0, -1)));
    assertTrue("Array opt int default implicit",
            0 == jsonArray.optInt(0));

    JSONArray nestedJsonArray = jsonArray.optJSONArray(9);
    assertTrue("Array opt JSONArray", nestedJsonArray != null);
    assertTrue("Array opt JSONArray default", 
            null == jsonArray.optJSONArray(99));

    JSONObject nestedJsonObject = jsonArray.optJSONObject(10);
    assertTrue("Array opt JSONObject", nestedJsonObject != null);
    assertTrue("Array opt JSONObject default", 
            null == jsonArray.optJSONObject(99));

    assertTrue("Array opt long",
            0 == jsonArray.optLong(11));
    assertTrue("Array opt long default",
            -2 == jsonArray.optLong(-1, -2));
    assertTrue("Array opt long default implicit",
            0 == jsonArray.optLong(-1));

    assertTrue("Array opt string",
            "hello".equals(jsonArray.optString(4)));
    assertTrue("Array opt string default implicit",
            "".equals(jsonArray.optString(-1)));
}
 
Example 17
Source File: CommonParser.java    From letv with Apache License 2.0 4 votes vote down vote up
protected JSONArray getJSONArray(JSONArray array, int index) {
    return array.optJSONArray(index);
}
 
Example 18
Source File: CommonParser.java    From letv with Apache License 2.0 4 votes vote down vote up
protected JSONArray getJSONArray(JSONArray array, int index) {
    return array.optJSONArray(index);
}