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

The following examples show how to use org.json.JSONArray#opt() . 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: HybridBridge.java    From ans-android-sdk with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unused")
private void profileAppend(Context context, JSONArray array) {
    if (array != null && array.length() > 0) {
        if (array.length() == 2) {
            String key = array.optString(0);
            Object value = array.opt(1);
            AnalysysAgent.profileAppend(context, key, value);
        } else {
            JSONObject obj = array.optJSONObject(0);
            if (obj != null && obj.length() > 0) {
                Map<String, Object> map = convertToMap(obj);
                AnalysysAgent.profileAppend(context, map);
            }
        }
    }
}
 
Example 2
Source File: ITeslaRules.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
public static void processTreeNode(JSONObject node, JSONArray inputs, String currentCondition, List<String> trueConditions, JSONObject stats, int trueIdx) {
    if ("thresholdTest".equals(node.optString("type"))) {
        int inputIdx = node.optInt("inputIndex");
        // conditional node
        String trueCondition = "("+inputs.opt(inputIdx)+" < "+node.optDouble("threshold")+")";
        String falseCondition = "("+inputs.opt(inputIdx)+" >= "+node.optDouble("threshold")+")";
        processTreeNode(node.optJSONObject("trueChild"), inputs, (currentCondition==null||currentCondition.length()==0)?trueCondition:(currentCondition+" and "+trueCondition), trueConditions, stats, trueIdx);
        processTreeNode(node.optJSONObject("falseChild"), inputs, (currentCondition==null||currentCondition.length()==0)?falseCondition:(currentCondition+" and "+falseCondition), trueConditions, stats, trueIdx);
    } else {
        String nodeIdx = node.optString("id");
        JSONArray nodeValues = stats.optJSONObject(nodeIdx).optJSONArray("counts");
        double purity = nodeValues.optInt(trueIdx) / (double)stats.optJSONObject(nodeIdx).optInt("count");
        if (purity > 0.95 && node.optBoolean("value")) {
            trueConditions.add(currentCondition == null ? "true" : currentCondition);
        }
    }
}
 
Example 3
Source File: JSONArrayObservable.java    From Tangram-Android with MIT License 6 votes vote down vote up
void run() {
    JSONArray a = array;
    int n = a.length();

    for (int i = 0; i < n && !isDisposed(); i++) {
        T value = (T) a.opt(i);
        if (value == null) {
            actual.onError(new NullPointerException("The " + i + "th element is null"));
            return;
        }
        actual.onNext(value);
    }
    if (!isDisposed()) {
        actual.onComplete();
    }
}
 
Example 4
Source File: DeviceController.java    From NewXmPluginSDK with Apache License 2.0 6 votes vote down vote up
/**
 * ApiLevel 79
 * 处理订阅消息
 *
 * @param data
 */
public void onSubscribeData(String data) {
    if (TextUtils.isEmpty(data)) return;
    try {
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonItem = jsonArray.optJSONObject(i);
            String key = jsonItem.optString("key");
            String[] items = key.split("\\.");
            if (items.length < 3) continue;
            PropertyController controller = getPropertyController(Integer.valueOf(items[1]), Integer.valueOf(items[2]));
            if (controller != null) {
                JSONArray dataArray = jsonItem.optJSONArray("value");
                if (dataArray == null || dataArray.length() == 0) continue;
                Object object = dataArray.opt(0);
                PropertyParam param = newPropertyParam(Integer.valueOf(items[1]), Integer.valueOf(items[2]), object);
                param.setResultCode(0);
                controller.updateValue(param, true);
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: JsonConverter.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
public static <T> List<T> listFromJson(JSONArray json) {
  if (json == null) {
    return null;
  }
  List<Object> result = new ArrayList<>(json.length());
  for (int i = 0; i < json.length(); i++) {
    Object value = json.opt(i);
    if (value == null || value == JSONObject.NULL) {
      value = null;
    } else if (value instanceof JSONObject) {
      value = mapFromJson((JSONObject) value);
    } else if (value instanceof JSONArray) {
      value = listFromJson((JSONArray) value);
    } else if (JSONObject.NULL.equals(value)) {
      value = null;
    }
    result.add(value);
  }
  return CollectionUtil.uncheckedCast(result);
}
 
Example 6
Source File: JsonToXml.java    From XmlToJson with Apache License 2.0 6 votes vote down vote up
private void prepareArray(Node node, String key, JSONArray array) {
    int count = array.length();
    String path = node.getPath() + "/" + key;
    for (int i = 0; i < count; ++i) {
        Node subNode = new Node(key, path);
        Object object = array.opt(i);
        if (object != null) {
            if (object instanceof JSONObject) {
                JSONObject jsonObject = (JSONObject) object;
                prepareObject(subNode, jsonObject);
            } else if (object instanceof JSONArray) {
                JSONArray subArray = (JSONArray) object;
                prepareArray(subNode, key, subArray);
            } else {
                String value = object.toString();
                subNode.setName(key);
                subNode.setContent(value);
            }
        }
        node.addChild(subNode);
    }
}
 
Example 7
Source File: RegisterActivity.java    From HomeApplianceMall with MIT License 6 votes vote down vote up
@Override
protected Object doInBackground(String... params) {
    boolean res = false;
    try {
        JSONArray jsonArray = new JSONArray(String.valueOf(util.getHttpJsonByhttpclient(params[0])));
        String status = null;//ok、no
        String msg = null;//registFalse、registSuccess
        JSONObject jsonObject2 = (JSONObject) jsonArray.opt(0);
        status = jsonObject2.getString("status");
        msg = jsonObject2.getString("msg");

        if(status.equals("ok")){
            res = true;
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return res;
}
 
Example 8
Source File: HybridBridge.java    From ans-android-sdk with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unused")
private void profileIncrement(Context context, JSONArray array) {
    if (array != null && array.length() > 0) {
        if (array.length() == 2) {
            String key = array.optString(0);
            Number value = (Number) array.opt(1);
            AnalysysAgent.profileIncrement(context, key, value);
        } else {
            JSONObject obj = array.optJSONObject(0);
            if (obj != null && obj.length() > 0) {
                Map<String, Number> map = convertToNumberMap(obj);
                AnalysysAgent.profileIncrement(context, map);
            }
        }
    }
}
 
Example 9
Source File: HybridBridge.java    From ans-android-sdk with GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unused")
private void profileSet(Context context, JSONArray array) {
    if (array != null && array.length() > 0) {
        if (array.length() == 2) {
            String key = array.optString(0);
            Object value = array.opt(1);
            AnalysysAgent.profileSet(context, key, value);
        } else {
            JSONObject obj = array.optJSONObject(0);
            if (obj != null && obj.length() > 0) {
                Map<String, Object> map = convertToMap(obj);
                AnalysysAgent.profileSet(context, map);
            }
        }
    }
}
 
Example 10
Source File: JSONObjectUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定索引数据
 * @param jsonArray {@link JSONArray}
 * @param index     索引
 * @param <T>       泛型
 * @return 指定 key 数据
 */
public static <T> T opt(final JSONArray jsonArray, final int index) {
    if (jsonArray != null && index >= 0) {
        try {
            return (T) jsonArray.opt(index);
        } catch (Exception e) {
            LogPrintUtils.eTag(TAG, e, "opt - JSONArray");
        }
    }
    return null;
}
 
Example 11
Source File: CacheConstants.java    From VideoOS-Android-SDK with GNU General Public License v3.0 5 votes vote down vote up
private static JSONArray reverse(JSONArray jsonArray) throws JSONException {
    for (int i = 0; i < jsonArray.length() / 2; i++) {
        Object temp = jsonArray.opt(i);
        jsonArray.put(i,jsonArray.opt(jsonArray.length() - 1 - i));
        jsonArray.put(jsonArray.length() - 1 - i, temp);
    }
    return jsonArray;
}
 
Example 12
Source File: ParameterCheck.java    From ans-android-sdk with GNU General Public License v3.0 5 votes vote down vote up
/**
 * json array 类型校验
 *
 * @throws
 */
private static void checkJsonArray(JSONArray jar) {
    for (int i = 0; i < jar.length(); i++) {
        if (jar.opt(i) instanceof Number) {
            LogBean.setDetails(Constants.CODE_FAILED, LogPrompt.TYPE_ERROR);
            return;
        }
    }
}
 
Example 13
Source File: Util.java    From prebid-mobile-android with Apache License 2.0 5 votes vote down vote up
@CheckResult
private static JSONArray removeEntryWithoutValue(@NonNull JSONArray array) throws JSONException {

    for (int i = 0; i < array.length(); i++) {

        Object value = array.opt(i);
        if (value != null) {

            if (value instanceof JSONObject) {

                JSONObject mapValue = (JSONObject) value;
                removeEntryWithoutValue(mapValue);

                if (mapValue.length() == 0) {
                    array = getJsonArrayWithoutEntryByIndex(array, i);
                }
            } else if (value instanceof JSONArray) {
                JSONArray arrayValue = (JSONArray) value;
                arrayValue = removeEntryWithoutValue(arrayValue);

                array.put(i, arrayValue);

                if (arrayValue.length() == 0) {
                    array = getJsonArrayWithoutEntryByIndex(array, i);
                }
            } else if (value instanceof String) {
                String stringValue = (String) value;

                if (stringValue.length() == 0) {
                    array = getJsonArrayWithoutEntryByIndex(array, i);
                }
            }
        }

    }

    return array;
}
 
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: GraphObjectFactoryTests.java    From FacebookImageShareIntent with MIT License 5 votes vote down vote up
@SmallTest
@MediumTest
@LargeTest
public void testCollectionPutOfWrapperPutsJSONObject() throws JSONException {
    JSONObject jsonObject = new JSONObject();

    GraphObject graphObject = GraphObject.Factory.create(jsonObject);
    graphObject.setProperty("hello", "world");
    graphObject.setProperty("hocus", "pocus");

    GraphObjectList<GraphObject> parentList = GraphObject.Factory
            .createList(GraphObject.class);
    parentList.add(graphObject);

    JSONArray jsonArray = parentList.getInnerJSONArray();

    Object obj = jsonArray.opt(0);

    assertNotNull(obj);
    assertEquals(jsonObject, obj);

    parentList.set(0, graphObject);

    obj = jsonArray.opt(0);

    assertNotNull(obj);
    assertEquals(jsonObject, obj);
}
 
Example 16
Source File: MixMessage.java    From sctalk with Apache License 2.0 5 votes vote down vote up
public static MixMessage parseFromDB(MessageEntity entity) throws JSONException {
    if(entity.getDisplayType() != DBConstant.SHOW_MIX_TEXT){
        throw new RuntimeException("#MixMessage# parseFromDB,not SHOW_MIX_TEXT");
    }
    Gson gson = new GsonBuilder().create();
    MixMessage mixMessage = new MixMessage(entity);
    List<MessageEntity> msgList = new ArrayList<>();
    JSONArray jsonArray = new JSONArray(entity.getContent());

    for (int i = 0, length = jsonArray.length(); i < length; i++) {
        JSONObject jsonOb = (JSONObject) jsonArray.opt(i);
        int displayType = jsonOb.getInt("displayType");
        String jsonMessage = jsonOb.toString();
        switch (displayType){
            case DBConstant.SHOW_ORIGIN_TEXT_TYPE:{
                TextMessage textMessage = gson.fromJson(jsonMessage,TextMessage.class);
                textMessage.setSessionKey(entity.getSessionKey());
                msgList.add(textMessage);
            }break;

            case DBConstant.SHOW_IMAGE_TYPE:
                ImageMessage imageMessage = gson.fromJson(jsonMessage,ImageMessage.class);
                imageMessage.setSessionKey(entity.getSessionKey());
                msgList.add(imageMessage);
                break;
        }
    }
    mixMessage.setMsgList(msgList);
    return mixMessage;
}
 
Example 17
Source File: HybridBridge.java    From ans-android-sdk with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unused")
private void registerSuperProperty(Context context, JSONArray array) {
    if (context != null) {
        if (array != null && array.length() > 0) {
            String key = array.optString(0);
            Object value = array.opt(1);
            AgentProcess.getInstance().registerJsSuperProperty(key,value);
        }
    }
}
 
Example 18
Source File: OrderFragment.java    From elemeimitate with Apache License 2.0 5 votes vote down vote up
public List<HashMap<String,Object>> getOrderList(String url,String account){
  	List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
  	
  	//同步加载的类
  	SyncHttp syncHttp = new SyncHttp();
  	
  	String params = "account=" + account;
  	
  	try {
	String retStr = syncHttp.httpGet(url, params);	
	JSONObject jsonObject = new JSONObject(retStr);
	
	int ret = jsonObject.getInt("ret");
	if(ret == 0){
		JSONObject dataObject = jsonObject.getJSONObject("data");
		int totalNum = dataObject.getInt("totalNum");
		if(totalNum > 0){
			JSONArray orderlist = dataObject.getJSONArray("orderList");
			for(int i = 0;i<orderlist.length();i++){
				JSONObject orderMap = (JSONObject)orderlist.opt(i);
				HashMap<String, Object> map = new HashMap<String,Object>();
				map.put("picPath", orderMap.getString("picPath"));
				map.put("name", orderMap.getString("name"));
				map.put("amount", orderMap.getInt("amount"));
				map.put("order_time", orderMap.get("order_time"));
				map.put("total_price", orderMap.getDouble("total_price"));
				map.put("status", orderMap.getString("status"));
				list.add(map);
			}
		}
	}else{
		
	}
} catch (Exception e) {
	e.printStackTrace();
}
  	return list;
  }
 
Example 19
Source File: EleFragment.java    From elemeimitate with Apache License 2.0 5 votes vote down vote up
public List<HashMap<String,Object>> getAllInfo(String url){
  	List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
  	String params = "";
  	
  	SyncHttp syncHttp = new SyncHttp();
  	try{
  		String retStr = syncHttp.httpGet(url, params);
  		JSONObject jsonObject = new JSONObject(retStr);
  		
  		int ret = jsonObject.getInt("ret");
  		if(ret==0){
  			JSONObject dataObject = jsonObject.getJSONObject("data");
  			
  			int totalNum = dataObject.getInt("totalNum");
  			if(totalNum>0){
  				JSONArray infoList = dataObject.getJSONArray("list");
  				for(int i=0;i<infoList.length();i++){
  					JSONObject infoMap = (JSONObject)infoList.opt(i);
  					HashMap<String,Object> map = new HashMap<String,Object>();
  					map.put("businessName", infoMap.get("businessName"));
  					map.put("sendOutPrice", infoMap.get("sendOutPrice"));
  					map.put("distributionPrice", infoMap.get("distributionPrice"));
  					map.put("shopHours", infoMap.get("shopHours"));
  					map.put("businessAddress", infoMap.get("businessAddress"));
  					map.put("businessDepict", infoMap.get("businessDepict"));
  					map.put("notice", infoMap.get("notice"));
  					map.put("businessScenery", infoMap.get("businessScenery"));
  					map.put("logo", infoMap.get("logo"));
  					list.add(map);
  				}
  			}
  		}
  		
  	}catch (Exception e) {
  		e.printStackTrace();
}
  	return list;
  }
 
Example 20
Source File: LoginActivity.java    From HomeApplianceMall with MIT License 4 votes vote down vote up
@Override
protected Object doInBackground(String... params) {
    boolean res = false;
    try {
        JSONArray jsonArray = new JSONArray(String.valueOf(util.getHttpJsonByhttpclient(params[0])));
        String status = null;
        String msg = null;//loginFalse、u、m
        String loginUserId = null;
        String loginUserName = null;
        String shoppingcarNum = null;
        String orderNumber = null;
        String sessionId = null;
        for(int i=0;i<jsonArray.length();i++){
            JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
            if(i==0){
                status = jsonObject2.getString("status");
                msg = jsonObject2.getString("msg");
            }else{
                loginUserId = jsonObject2.getString("loginUserId");
                loginUserName = jsonObject2.getString("loginUserName");
                orderNumber = jsonObject2.getString("orderNum");
                sessionId = jsonObject2.getString("sessionId");
                if(msg.equals("u")){
                    shoppingcarNum = jsonObject2.getString("shoppingcarNum");
                }
            }
        }
        if(shoppingcarNum==null || shoppingcarNum.equals("null")){
            shoppingcarNum = "0";
        }
        if(orderNumber==null){
            orderNumber = "0";
        }

        if(status!=null && status.equals("ok")){
            myApplication.setB_login(true);
            myApplication.setS_loginUserId(loginUserId);
            myApplication.setS_loginUserKind(msg);
            myApplication.setS_loginUserName(loginUserName);
            myApplication.setNumberOrder(Integer.parseInt(orderNumber));
            myApplication.setNumberShoppingCar(Integer.parseInt(shoppingcarNum));
            myApplication.setSessionId(sessionId);
            res = true;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return res;
}