Java Code Examples for com.alibaba.fastjson.JSONArray

The following are top voted examples for showing how to use com.alibaba.fastjson.JSONArray. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: dble   File: FileSystemRepository.java   Source Code and License 7 votes vote down vote up
/**
 * read the json file and transform into memory
 *
 * @return
 * @throws Exception
 */
public Map<String, Map<String, String>> getObject() throws Exception {
    Map<String, Map<String, String>> result = new ConcurrentHashMap<String, Map<String, String>>();
    String jsonString = readFromFile();
    JSONArray jsonArray = JSONObject.parseArray(jsonString);
    if (jsonArray != null) {
        for (Object schema : jsonArray) {
            JSONObject x = (JSONObject) schema;
            String schemaName = x.getString("schema");
            JSONArray viewList = x.getJSONArray("list");
            Map<String, String> schemaView = new ConcurrentHashMap<String, String>();
            for (Object view : viewList) {
                JSONObject y = (JSONObject) view;
                schemaView.put(y.getString("name"), y.getString("sql"));
            }
            result.put(schemaName, schemaView);
        }
    }
    return result;
}
 
Example 2
Project: attendance   File: StatisAction.java   Source Code and License 7 votes vote down vote up
@RequestMapping("getUserReport.do")
public void getUserreport(HttpServletResponse response){
	List<Report> list=timetableservice.getAllUserReport();
	List<Object> list_array=new ArrayList<Object>();
	
	for(Report item :list){
		list_array.add(item);
	}
	JSONArray array=new JSONArray(list_array);
	try {
		response.getWriter().print(array);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 3
Project: GitHub   File: Issue1492.java   Source Code and License 6 votes vote down vote up
public void test_for_issue() throws Exception {
    DubboResponse resp = new DubboResponse();

    // test for JSONObject
    JSONObject obj = new JSONObject();
    obj.put("key1","value1");
    obj.put("key2","value2");
    resp.setData(obj);

    String str = JSON.toJSONString(resp);
    System.out.println(str);
    DubboResponse resp1 = JSON.parseObject(str, DubboResponse.class);
    assertEquals(str, JSON.toJSONString(resp1));

    // test for JSONArray
    JSONArray arr = new JSONArray();
    arr.add("key1");
    arr.add("key2");
    resp.setData(arr);

    String str2 = JSON.toJSONString(resp);
    System.out.println(str2);
    DubboResponse resp2 = JSON.parseObject(str2, DubboResponse.class);
    assertEquals(str2, JSON.toJSONString(resp2));

}
 
Example 4
Project: weex-3d-map   File: WXDomObjectTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testClone() throws Exception {
  JSONObject.parseObject("{\"ref\":\"100\",\"type\":\"div\",\"attr\":{},\"style\":{\"backgroundColor\":\"rgb(40,96,144)\",\"fontSize\":40,\"color\":\"#ffffff\",\"paddingRight\":30,\"paddingLeft\":30,\"paddingBottom\":20,\"paddingTop\":20}}");
  JSONObject obj = new JSONObject();
  obj.put("ref","101");
  obj.put("type","test");

  JSONArray event = new JSONArray();
  event.add("click");
  obj.put("event",event);
  dom.parseFromJson(obj);

  WXDomObject clone = dom.clone();
  assertEquals(clone.getRef(),"101");
  assertEquals(clone.getType(),"test");

}
 
Example 5
Project: GitHub   File: JSONReaderScannerTest_int.java   Source Code and License 6 votes vote down vote up
public void test_scanInt() throws Exception {
    StringBuffer buf = new StringBuffer();
    buf.append('[');
    for (int i = 0; i < 1024; ++i) {
        if (i != 0) {
            buf.append(',');
        }
        buf.append(i);
    }
    buf.append(']');

    Reader reader = new StringReader(buf.toString());

    JSONReaderScanner scanner = new JSONReaderScanner(reader);

    DefaultJSONParser parser = new DefaultJSONParser(scanner);
    JSONArray array = (JSONArray) parser.parse();
    for (int i = 0; i < array.size(); ++i) {
        Assert.assertEquals(i, ((Integer) array.get(i)).intValue()); 
    }
}
 
Example 6
Project: eagle-oj-api   File: IndexController.java   Source Code and License 6 votes vote down vote up
@ApiOperation("用户登入")
@PostMapping("/login")
public ResponseEntity login(@RequestBody @Valid IndexLoginFormat format) {
    UserEntity userEntity = userService.getUserByLogin(format.getEmail(),
            new Md5Hash(format.getPassword()).toString());
    if (userEntity == null)
        throw new WebErrorException("用户名密码错误");

    JSONArray array = userEntity.getPermission();
    Iterator<Object> it = array.iterator();
    Set<String> permission = new HashSet<>();
    while (it.hasNext()) {
        permission.add(it.next().toString());
    }
    String token = JWTUtil.sign(userEntity.getUid(), userEntity.getRole(), permission, userEntity.getPassword());
    Cache<String, String> authCache = CacheController.getAuthCache();
    authCache.put(token, userEntity.getPassword());

    return new ResponseEntity("登入成功", token);
}
 
Example 7
Project: eagle-oj-api   File: ProblemService.java   Source Code and License 6 votes vote down vote up
public int addProblem(int owner, String title, JSONObject description, JSONObject inputFormat, JSONObject outputFormat,
                      int difficult, JSONArray samples, int time, int memory) {
    // 添加题目
    ProblemEntity problemEntity = new ProblemEntity();
    problemEntity.setOwner(owner);
    problemEntity.setTitle(title);
    problemEntity.setLang(JudgeHelper.getAllLanguages());
    problemEntity.setDescription(description);
    problemEntity.setInputFormat(inputFormat);
    problemEntity.setOutputFormat(outputFormat);
    problemEntity.setDifficult(difficult);
    problemEntity.setSamples(samples);
    problemEntity.setTime(time);
    problemEntity.setMemory(memory);
    problemEntity.setStatus(0);
    problemEntity.setCreateTime(System.currentTimeMillis());

    return problemDao.addProblem(sqlSession, problemEntity)? problemEntity.getPid() : 0;
}
 
Example 8
Project: pay-xxpay-master   File: PayOrderController.java   Source Code and License 6 votes vote down vote up
@RequestMapping("/list")
@ResponseBody
public String list(@ModelAttribute PayOrder payOrder, Integer pageIndex, Integer pageSize) {
    PageModel pageModel = new PageModel();
    int count = payOrderService.count(payOrder);
    if(count <= 0) return JSON.toJSONString(pageModel);
    List<PayOrder> payOrderList = payOrderService.getPayOrderList((pageIndex-1)*pageSize, pageSize, payOrder);
    if(!CollectionUtils.isEmpty(payOrderList)) {
        JSONArray array = new JSONArray();
        for(PayOrder po : payOrderList) {
            JSONObject object = (JSONObject) JSONObject.toJSON(po);
            if(po.getCreateTime() != null) object.put("createTime", DateUtil.date2Str(po.getCreateTime()));
            if(po.getAmount() != null) object.put("amount", AmountUtil.convertCent2Dollar(po.getAmount()+""));
            array.add(object);
        }
        pageModel.setList(array);
    }
    pageModel.setCount(count);
    pageModel.setMsg("ok");
    pageModel.setRel(true);
    return JSON.toJSONString(pageModel);
}
 
Example 9
Project: tulingchat   File: DailyZhihuUtil.java   Source Code and License 6 votes vote down vote up
public List<Article> getNewsListFromJsonArray(JSONArray jsonArray) {
	List<Article> list = new ArrayList<>();
	int size = jsonArray.size();
	int lastindex = 0;
	if (size >= 5) {
		lastindex = 5;
	} else {
		lastindex = size;
	}
	for (int i = 0; i < lastindex; i++) {
		JSONObject object = jsonArray.getJSONObject(i);
		String id = object.getString("id");//消息内容Id
		String replaceUrl = newsUrl.replace("id", id);
		String s = HttpClientUtil.sendGet(replaceUrl, null, null);
		JSONObject jo = JSONObject.parseObject(s);
		Article article = new Article();
		article.setTitle(jo.getString("title"));
		article.setDescription("");
		article.setPicUrl(jo.getString("image"));
		article.setUrl(jo.getString("share_url"));
		list.add(article);
	}
	return list;
}
 
Example 10
Project: rainbow   File: RwMain.java   Source Code and License 6 votes vote down vote up
private void savePipelineState(Pipeline pipeline, String state, String time) {
    State s = new State(time, state);
    Process p = searchProcessByPno(pipeline.getNo());
    if (p != null) {
        p.getPipelineState().add(s);
    } else {
        List<State> PipelineState = new ArrayList<>();
        PipelineState.add(s);
        p = new Process(pipeline.getNo(), PipelineState);
        SysConfig.ProcessList.add(p);
    }
    String processListJson = JSONArray.toJSONString(SysConfig.ProcessList);
    try {
        FileUtil.writeFile(processListJson, SysConfig.Catalog_Project + "cashe/process.txt");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 11
Project: KettleEasyExpand   File: DataValidate.java   Source Code and License 6 votes vote down vote up
/**
* 不匹配 <br/>
* @author jingma
* @param object
* @param vi
* @param validateInfo
*/
private boolean validateNotLike(Object object, JSONObject vi, JSONArray validateInfo) {
    if(object==null){
        return true;
    }
    List<String> dataList = getValidateData(vi);
    boolean result = true;
    for(String val:dataList){
        if(object.toString().indexOf(val)>-1){
            result = false;
            break;
        }
    }
    if(!result){
        vi.put(VALIDATE_VAL, object.toString());
        validateInfo.add(vi);
    }
    return result;
}
 
Example 12
Project: GitHub   File: LexerTest.java   Source Code and License 6 votes vote down vote up
public void test_number() throws Exception {
    String text = "[0,1,-1,2E3,2E+3,2E-3,2e3,2e+3,2e-3]";
    JSONArray array = JSON.parseArray(text);

    Assert.assertEquals(0, array.get(0));
    Assert.assertEquals(1, array.get(1));
    Assert.assertEquals(-1, array.get(2));
    Assert.assertEquals(new BigDecimal("2E3"), array.get(3));
    Assert.assertEquals(new BigDecimal("2E3"), array.get(4));
    Assert.assertEquals(new BigDecimal("2E-3"), array.get(5));
    Assert.assertEquals(new BigDecimal("2E3"), array.get(6));
    Assert.assertEquals(new BigDecimal("2E3"), array.get(7));
    Assert.assertEquals(new BigDecimal("2E-3"), array.get(8));

    for (long i = Long.MIN_VALUE; i <= Long.MIN_VALUE + 1000 * 10; ++i) {
        Assert.assertEquals(i, JSON.parse(Long.toString(i)));
    }

    for (long i = Long.MAX_VALUE - 1000 * 10; i <= Long.MAX_VALUE && i > 0; ++i) {
        Assert.assertEquals(i, JSON.parse(Long.toString(i)));
    }
}
 
Example 13
Project: xxpay-master   File: MchNotifyController.java   Source Code and License 6 votes vote down vote up
@RequestMapping("/list")
@ResponseBody
public String list(@ModelAttribute MchNotify mchNotify, Integer pageIndex, Integer pageSize) {
    PageModel pageModel = new PageModel();
    int count = mchNotifyService.count(mchNotify);
    if(count <= 0) return JSON.toJSONString(pageModel);
    List<MchNotify> mchNotifyList = mchNotifyService.getMchNotifyList((pageIndex-1)*pageSize, pageSize, mchNotify);
    if(!CollectionUtils.isEmpty(mchNotifyList)) {
        JSONArray array = new JSONArray();
        for(MchNotify po : mchNotifyList) {
            JSONObject object = (JSONObject) JSONObject.toJSON(po);
            if(po.getCreateTime() != null) object.put("createTime", DateUtil.date2Str(po.getCreateTime()));
            if(po.getLastNotifyTime() != null) object.put("lastNotifyTime", DateUtil.date2Str(po.getLastNotifyTime()));
            array.add(object);
        }
        pageModel.setList(array);
    }
    pageModel.setCount(count);
    pageModel.setMsg("ok");
    pageModel.setRel(true);
    return JSON.toJSONString(pageModel);
}
 
Example 14
Project: easyweb   File: DictController.java   Source Code and License 6 votes vote down vote up
/**
 * 获取所有机构列表
 * @return
 */
@ApiOperation(value = "字典管理-树层级结构接口")
@PostMapping("/tree")
@ResponseBody
public JSONArray tree(SysDict model) {
    JSONArray list=new JSONArray();
    List<SysDict> midList = service.getDicByParentId(model.getId());
    if(midList!=null){
        for (SysDict item:midList) {
            JSONObject obj=new JSONObject();
            obj.put("name",item.getLabel());
            obj.put("id",item.getValue());
            obj.put("pId",item.getParentId());
            obj.put("isParent",""+isHaveChild(item.getId()));
            list.add(obj);
        }
    }
    return list;
}
 
Example 15
Project: APIJSON-Android-RxJava   File: JSON.java   Source Code and License 6 votes vote down vote up
/**判断是否为JSONArray
 * @param obj instanceof String ? parseArray
 * @return
 */
public static boolean isJSONArray(Object obj) {
	if (obj instanceof JSONArray) {
		return true;
	}
	if (obj instanceof String) {
		try {
			JSONArray json = parseArray((String) obj);
			return json != null && json.isEmpty() == false;
		} catch (Exception e) {
			Log.e(TAG, "isJSONArray  catch \n" + e.getMessage());
		}
	}
	
	return false;
}
 
Example 16
Project: smartqq-agreement-core   File: JSON2Entity.java   Source Code and License 6 votes vote down vote up
/**
 * 解析讨论组信息
 * <p>Function: getDiscusList</p>
 * <p>Description: </p>
 *
 * @param content
 * @return
 * @author [email protected]
 * @date 2017年6月14日 下午4:06:12
 * @version 1.0
 */
public static DiscusList getDiscusList(String content) {
    DiscusList discusList = new DiscusList();
    try {
        JSONObject discusListJson = FastJson.toJSONObject(content);
        JSONObject result = (JSONObject) discusListJson.get("result");

        Map<Long, DiscuInfo> discuInfo = new HashMap<Long, DiscuInfo>();

        JSONArray array = (JSONArray) result.get("dnamelist");
        DiscuInfo discu;
        Object[] objs = array.toArray();
        for (Object obj : objs) {
            discu = FastJson.toObject(obj.toString(), DiscuInfo.class);
            discuInfo.put(discu.getDid(), discu);
        }
        discusList.setDiscus(discuInfo);
    } catch (Exception e) {
        logger.error("解析getDiscusList返回数据失败", e);
        return null;
    }
    return discusList;
}
 
Example 17
Project: xxpay-master   File: PayChannelController.java   Source Code and License 6 votes vote down vote up
@RequestMapping("/list")
@ResponseBody
public String list(@ModelAttribute PayChannel payChannel, Integer pageIndex, Integer pageSize) {
    PageModel pageModel = new PageModel();
    int count = payChannelService.count(payChannel);
    if(count <= 0) return JSON.toJSONString(pageModel);
    List<PayChannel> payChannelList = payChannelService.getPayChannelList((pageIndex-1)*pageSize, pageSize, payChannel);
    if(!CollectionUtils.isEmpty(payChannelList)) {
        JSONArray array = new JSONArray();
        for(PayChannel pc : payChannelList) {
            JSONObject object = (JSONObject) JSONObject.toJSON(pc);
            object.put("createTime", DateUtil.date2Str(pc.getCreateTime()));
            array.add(object);
        }
        pageModel.setList(array);
    }
    pageModel.setCount(count);
    pageModel.setMsg("ok");
    pageModel.setRel(true);
    return JSON.toJSONString(pageModel);
}
 
Example 18
Project: weex-uikit   File: NativeInvokeHelper.java   Source Code and License 6 votes vote down vote up
public Object invoke(final Object target,final Invoker invoker,JSONArray args) throws Exception {
  final Object[] params = prepareArguments(
      invoker.getParameterTypes(),
      args);
  if (invoker.isRunOnUIThread()) {
    WXSDKManager.getInstance().postOnUiThread(new Runnable() {
      @Override
      public void run() {
        try {
          invoker.invoke(target, params);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    });
  } else {
    return invoker.invoke(target, params);
  }
  return null;
}
 
Example 19
Project: ssm-rbac   File: RoleController.java   Source Code and License 6 votes vote down vote up
/**
 * 获得全部资源以及已经授权的资源的checkbox树
 */
@RequestMapping("toGrant")
public String toGrant(@RequestParam("rid") int rid, Model model) {
    List<RoleFormBean> rightDataByRid = roleService.findRightDataByRid(rid);
    List<String> rightFids = new ArrayList<>();
    for (RoleFormBean roleFormBean : rightDataByRid) {
        String prefix = "m";
        if (roleFormBean.getType() == 1) {
            prefix = "f";
        }
        rightFids.add(prefix + roleFormBean.getFid());
    }
    List<RoleCheckedFormBean> checkedRightDataByRid = roleService.findCheckedRightDataByRid(rid);
    List<RoleCheckedFormBean> newList = new ArrayList<>();
    for (RoleCheckedFormBean checkedFormBean : checkedRightDataByRid) {
        if (rightFids.contains(checkedFormBean.getId())) {
            checkedFormBean.setChecked(true);
        }
        newList.add(checkedFormBean);
    }
    model.addAttribute("treeData", JSONArray.toJSON(CommonUtils.buildCheckedRightTree(newList)));
    return "role/grant";
}
 
Example 20
Project: ontology_setting   File: OntologyController.java   Source Code and License 6 votes vote down vote up
@RequestMapping(value = "/get-ontology-list", method = RequestMethod.GET)
@ResponseBody
public JSONArray getOntologyList(@RequestParam(value = "type", required = false) String type) {
    logger.info(" [Http request get ontology list] type = {} ", type);
    List<Ontology> ontologyList;
    if (type == null || "".equals(type)) {
        ontologyList = ontologyService.getAllOntology();
    } else {
        ontologyList = ontologyService.getOntologyByType(type);
    }
    JSONArray jsonArray = new JSONArray();
    for (Ontology ontology : ontologyList) {
        JSONObject obj = new JSONObject(true);
        obj.put("key", ontology.getId());
        obj.put("name", ontology.getName());
        obj.put("type", ontology.getOntologyType() == null ? "" : ontology.getOntologyType().getName());
        obj.put("category_name", ontology.getOntologyCategory() == null ? "" : ontology.getOntologyCategory().getName());
        obj.put("valid", ontology.getValid());
        obj.put("creator", ontology.getCreator());
        obj.put("create_time", DateUtil.format(ontology.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        obj.put("update_time", DateUtil.format(ontology.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
        jsonArray.add(obj);
    }
    return jsonArray;
}
 
Example 21
Project: SimpleProcessControl   File: ProcessCRUDService.java   Source Code and License 6 votes vote down vote up
private List<ProcessOrder> getProcessOrders(ProcessPo processPo) {
    JSONArray jsonArray = JSON.parseArray(processPo.getProcessOrder());
    List<ProcessOrder> processOrders = new ArrayList<>();
    for (int i = 0; i < jsonArray.size(); i++) {
        ProcessOrder processOrder = new ProcessOrder();
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        processOrder.setProcessOrder(jsonObject.getInteger("processOrder"));
        try {
            processOrder.setProcessClass(Class.forName(jsonObject.getString("processClazz")));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        processOrders.add(processOrder);
    }
    return processOrders;
}
 
Example 22
Project: SweepRobot   File: JSON.java   Source Code and License 6 votes vote down vote up
private static Object convertElementToField(Object element, Class fc, Field f, Registry<Class> r) {
    //System.out.println("JSON.convertElementToField: " + f.getName() + " " + fc.getName());
    Object value;
    if (element.getClass().equals(JSONObject.class)) {
        //System.out.println("JSON.convertElementToField: JSON Object " + ((JSONObject) element).toJSONString());
        value = convertJSONObjectToMessage((JSONObject) element, fc, r);
    }
    else if (element.getClass().equals(JSONArray.class)) {
        //System.out.println("JSON.convertElementToField: JSON Array " + ((JSONArray) element).toJSONString());
        if (Indication.asArray(f))
            value = convertJSONArrayToMessage((JSONArray) element, fc, r);
        else value = convertJSONArrayToArray((JSONArray) element, fc, r);
    }
    else {
        //System.out.println("JSON.convertElementToField: Primitive " + element);
        if (Indication.isBase64Encoded(f))
            value = convertBase64JSONStringToByteArray(element);
        else value = convertJSONPrimitiveToPrimitive(element, fc);
    }
     
    return value;        
}
 
Example 23
Project: TPondof   File: TagManager.java   Source Code and License 6 votes vote down vote up
public static List<Tag> getTags (boolean useCache) throws APIException {
    if (DEBUG) Log.i(TAG, "-> getTags");
    try {
        String text = NetworkUtil.get(ApiManager.API_TAGS, useCache);
        if (DEBUG) Log.i(TAG, "-> get -> success");
        JSONObject root = JSON.parseObject(text);
        JSONArray data = root.getJSONArray("data");
        List<Tag> tags = new ArrayList<>();
        for (int i = 0; i < data.size(); i ++) {
            JSONObject object = data.getJSONObject(i);
            Tag tag = getTag(object.getInteger("id"), object);
            if (DEBUG) Log.i(TAG, "Adding " + tag.toString());
            tags.add(tag);
        }
        return tags;
    } catch (IOException|JSONException e) {
        throw new APIException(e);
    }
}
 
Example 24
Project: GitHub   File: JSON.java   Source Code and License 5 votes vote down vote up
/**
 * @param json
 * @return
 */
public static JSONArray parseArray(String json) {
	try {
		return com.alibaba.fastjson.JSON.parseArray(getCorrectJson(json));
	} catch (Exception e) {
		Log.e(TAG, "parseArray  catch \n" + e.getMessage());
	}
	return null;
}
 
Example 25
Project: vscrawler   File: TableEvaluator.java   Source Code and License 5 votes vote down vote up
public static JSONArray toJson(List<List<Pair<String, String>>> input) {
    JSONArray jsonArray = new JSONArray();
    for (List<Pair<String, String>> pairs : input) {
        JSONObject itemJson = new JSONObject();
        for (Pair<String, String> pair : pairs) {
            itemJson.put(pair.getLeft(), pair.getRight());
        }
        jsonArray.add(itemJson);
    }

    return jsonArray;
}
 
Example 26
Project: upgradeToy   File: ParseMileage.java   Source Code and License 5 votes vote down vote up
@Test
public void test_dayData() {
    File file = new File("D:\\dayData.json");
    String json = readToString(file, "UTF-8");
    JSONArray dataArray = JSON.parseArray(json);
    JSONObject jsonObject = JSON.parseObject(json);
    System.out.println(jsonObject.toJSONString());
    double result = 0;
    for (int i = 0; i < dataArray.size(); i++) {
        JSONObject temp = JSON.parseObject(json);
        result += Double.parseDouble(temp.get("mileage").toString());
    }
    System.out.println(result);
}
 
Example 27
Project: GitHub   File: ResolveFieldDeserializer.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void setValue(Object object, Object value) {
    if (map != null) {
        map.put(key, value);
        return;
    }
    
    if (collection != null) {
        collection.add(value);
        return;
    }
    
    list.set(index, value);

    if (list instanceof JSONArray) {
        JSONArray jsonArray = (JSONArray) list;
        Object array = jsonArray.getRelatedArray();

        if (array != null) {
            int arrayLength = Array.getLength(array);

            if (arrayLength > index) {
                Object item;
                if (jsonArray.getComponentType() != null) {
                    item = TypeUtils.cast(value, jsonArray.getComponentType(), parser.getConfig());
                } else {
                    item = value;
                }
                Array.set(array, index, item);
            }
        }
    }
}
 
Example 28
Project: GitHub   File: TestIssues569.java   Source Code and License 5 votes vote down vote up
@Test
public void testBug569() {
    //第一次反序列化是使用的 MyResponse, 没有指定泛型类型,貌似会缓存 MyResponse, 后面在调用的MyResponse<?>反序列化就受影响了
    MyResponse resp1 = JSON.parseObject(jsonData, mType1, configBug569, featureValues,
            features != null ? features : EMPTY_SERIALIZER_FEATURES);

    //expect MyResponse<JSONArray<JSONObject>>
    MyResponse resp = JSON.parseObject(jsonData, mType, configBug569, featureValues,
            features != null ? features : EMPTY_SERIALIZER_FEATURES);
    Assert.assertNotNull(resp);
    Assert.assertNotNull(resp.getResult());
    Assert.assertEquals(JSONArray.class, resp.getResult().getClass());//这里会受到 resp1 的影响
}
 
Example 29
Project: rainbow   File: RwMain.java   Source Code and License 5 votes vote down vote up
private void saveCurLayout() {
    String aJson = JSONArray.toJSONString(SysConfig.CurLayout);
    try {
        FileUtil.writeFile(aJson, SysConfig.Catalog_Project + "cashe/curLayout.txt");
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 30
Project: Spring-Boot-Server   File: AppUserHealthRestful.java   Source Code and License 5 votes vote down vote up
/**
	 * 用户健康信息
	 * @return
	 */
	@RequestMapping(value = "/get")
	@ResponseBody
	public PageData getUserHealthData(@RequestBody PageData pd) throws Exception {
		if(StringUtils.isBlank(pd.getString("UI_IDCARD"))){
		return WebResult.requestFailed(10001, "参数缺失!", null);
	}else{
		HashMap<String,String> params = new HashMap<String,String> ();
//		params.put("idCardNo", "371323199401023411");
		params.put("idCardNo", pd.getString("UI_IDCARD"));
		List<UHeader> headerList = new ArrayList<UHeader>();
		UHeader conType = new UHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		headerList.add(conType);
		String result = HttpUtils.getPostResponse(tjUrl, params, headerList);
		if(!"".equals(result)){
			result = Des.decrypt(result);
			HashMap mp = JSON.parseObject(result, HashMap.class);
			JSONArray datalist = (JSONArray) mp.get("dataList");
			List dataList= new ArrayList();
			for(int i=0;i<datalist.size();i++){
				dataList.add(JSON.parseObject(((JSONObject)datalist.get(i)).toJSONString(),HashMap.class));
			}
			try {
				listSort(dataList);
				if(dataList.size()>0){
					dataList.get(0);
					return WebResult.requestSuccess(dataList.get(0));
				}else{
					return WebResult.requestSuccess(null);
				}
			} catch (Exception e) {
//				e.printStackTrace();
				return WebResult.requestFailed(100, "排序失败!", null);
			}
		}else{
			return WebResult.requestSuccess(null);
		}
	}
	}
 
Example 31
Project: eagle-oj-api   File: ProblemService.java   Source Code and License 5 votes vote down vote up
public boolean updateProblemDescription(int pid, String title, JSONObject description, JSONObject inputFormat,
                                        JSONObject outputFormat, JSONArray samples, int difficult) {
    //通过pid来更新题目
    ProblemEntity problemEntity = new ProblemEntity();
    problemEntity.setPid(pid);
    problemEntity.setTitle(title);
    problemEntity.setDescription(description);
    problemEntity.setInputFormat(inputFormat);
    problemEntity.setOutputFormat(outputFormat);
    problemEntity.setSamples(samples);
    problemEntity.setDifficult(difficult);
    return problemDao.updateProblemDescription(sqlSession, problemEntity);
}
 
Example 32
Project: GitHub   File: JSONReaderTest_array_array.java   Source Code and License 5 votes vote down vote up
public void test_read_1() throws Exception {
    JSONReader reader = new JSONReader(new JSONScanner(text));
    reader.startArray();

    int count = 0;
    while (reader.hasNext()) {
        Object item = reader.readObject();
        Assert.assertEquals(JSONArray.class, item.getClass());
        count++;
    }
    Assert.assertEquals(10, count);

    reader.endArray();
    reader.close();
}
 
Example 33
Project: westjson   File: WestJsonCompacter.java   Source Code and License 5 votes vote down vote up
public JSON compact(JSON object) {
    JSON result = object;
    if (object instanceof JSONObject) {
        result = compactConvert((JSONObject) object);
    } else if (object instanceof JSONArray) {
        result = compactConvert((JSONArray) object);
    }

    return result;
}
 
Example 34
Project: ucar-weex-core   File: WXDomObject.java   Source Code and License 5 votes vote down vote up
/**
 * Parse the jsonObject to {@link WXDomObject} recursively
 * @param map the original JSONObject
 */
public void parseFromJson(JSONObject map){
  if (map == null || map.size() <= 0) {
    return;
  }

  String type = (String) map.get("type");
  this.mType = type;
  this.mRef = (String) map.get("ref");
  Object style = map.get("style");
  if (style != null && style instanceof JSONObject) {
    WXStyle styles = new WXStyle();
    styles.putAll((JSONObject) style,false);
    this.mStyles = styles;
  }
  Object attr = map.get("attr");
  if (attr != null && attr instanceof JSONObject) {
    WXAttr attrs = new WXAttr((JSONObject) attr);
    //WXJsonUtils.putAll(attrs, (JSONObject) attr);
    this.mAttributes = attrs;
  }
  Object event = map.get("event");
  if (event != null && event instanceof JSONArray) {
    WXEvent events = new WXEvent();
    JSONArray eventArray = (JSONArray) event;
    int count = eventArray.size();
    for (int i = 0; i < count; ++i) {
      events.add(eventArray.getString(i));
    }
    this.mEvents = events;
  }

}
 
Example 35
Project: GitHub   File: StringTest_01.java   Source Code and License 5 votes vote down vote up
public void test_string() throws Exception {
    char[] chars = new char[1024];
    Arrays.fill(chars, '0');
    StringBuilder buf = new StringBuilder();
    buf.append("[\"");
    for (int i = 0; i < 16; ++i) {
        buf.append("\\\\");
        buf.append("\\\"");
        buf.append(new String(chars));
    }
    buf.append("\"]");
    
    String text = buf.toString();
    JSONArray array = (JSONArray) JSON.parse(text);
    Assert.assertEquals(1, array.size());
    
    String item = (String) array.get(0);
    Assert.assertEquals(16 * 1024 + 32, item.length());
    
    for (int i = 0; i < 16; ++i) {
        Assert.assertTrue(item.charAt(i * 1026) == '\\');
        Assert.assertTrue(item.charAt(i * 1026 + 1) == '\"');
        for (int j = 0; j < 1024; ++j) {
            Assert.assertTrue(item.charAt(i * 1026 + j + 2) == '0');    
        }
    }
}
 
Example 36
Project: KettleEasyExpand   File: DataValidate.java   Source Code and License 5 votes vote down vote up
/**
* 验证时间格式 <br/>
* @author jingma
* @param dateStr
* @param validateInfo 
* @param vi 
 * @return 
*/
private boolean validateDateFormat(Object dateStr, JSONObject vi, JSONArray validateInfo) {
    if(dateStr==null){
        return true;
    }
    Date date = DateUtil.parseDate(dateStr.toString());
    if(date==null){
        vi.put(VALIDATE_VAL, dateStr);
        validateInfo.add(vi);
        return false;
    }else{
        return true;
    }
}
 
Example 37
Project: ucar-weex-core   File: ArgumentsUtil.java   Source Code and License 5 votes vote down vote up
public static void fromArrayToBundle(Bundle bundle, String key, Object array) {
    if (bundle != null && !TextUtils.isEmpty(key) && array != null) {
        if (array instanceof String[]) {
            bundle.putStringArray(key, (String[]) ((String[]) array));
        } else if (array instanceof byte[]) {
            bundle.putByteArray(key, (byte[]) ((byte[]) array));
        } else if (array instanceof short[]) {
            bundle.putShortArray(key, (short[]) ((short[]) array));
        } else if (array instanceof int[]) {
            bundle.putIntArray(key, (int[]) ((int[]) array));
        } else if (array instanceof long[]) {
            bundle.putLongArray(key, (long[]) ((long[]) array));
        } else if (array instanceof float[]) {
            bundle.putFloatArray(key, (float[]) ((float[]) array));
        } else if (array instanceof double[]) {
            bundle.putDoubleArray(key, (double[]) ((double[]) array));
        } else if (array instanceof boolean[]) {
            bundle.putBooleanArray(key, (boolean[]) ((boolean[]) array));
        } else if (array instanceof char[]) {
            bundle.putCharArray(key, (char[]) ((char[]) array));
        } else {
            if (!(array instanceof JSONArray)) {
                throw new IllegalArgumentException("Unknown array type " + array.getClass());
            }

            ArrayList arraylist = new ArrayList();
            JSONArray jsonArray = (JSONArray) array;
            Iterator it = jsonArray.iterator();

            while (it.hasNext()) {
                JSONObject object = (JSONObject) it.next();
                arraylist.add(fromJsonToBundle(object));
            }

            bundle.putParcelableArrayList(key, arraylist);
        }

    }
}
 
Example 38
Project: boohee_v5.6   File: AtomicIntegerArrayCodec.java   Source Code and License 5 votes vote down vote up
public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName) {
    if (parser.getLexer().token() == 8) {
        parser.getLexer().nextToken(16);
        return null;
    }
    Collection array = new JSONArray();
    parser.parseArray(array);
    T atomicArray = new AtomicIntegerArray(array.size());
    for (int i = 0; i < array.size(); i++) {
        atomicArray.set(i, array.getInteger(i).intValue());
    }
    return atomicArray;
}
 
Example 39
Project: SuitAgent   File: DockerMetrics.java   Source Code and License 5 votes vote down vote up
/**
 * 内存
 * @param containerName
 * @param container
 * @return
 * @throws IOException
 */
private List<CollectObject> getMemMetrics(String containerName,JSONObject container,JSONObject machineInfo) throws IOException {
    List<CollectObject> collectObjectList = new ArrayList<>();

    boolean hasMemory = container.getJSONObject("spec").getBoolean("has_memory");
    collectObjectList.add(new CollectObject(containerName,"has_memory",hasMemory ? "1" : "0",""));

    if(hasMemory){
        long machineMemory = machineInfo.getLong("memory_capacity");//机器总内存
        long limitMemory = container.getJSONObject("spec").getJSONObject("memory").getLong("limit");//容器的内存限制大小
        if(limitMemory > machineMemory || limitMemory < 0){
            //若内存限制大于机器总内存或小于0,使用机器总内存为总内存大小
            limitMemory = machineMemory;
        }
        JSONArray stats = container.getJSONArray("stats");
        int count = stats.size();
        JSONObject stat = stats.getJSONObject(count - 1);
        JSONObject memory = stat.getJSONObject("memory");

        long usage = memory.getLong("usage");
        long cache = memory.getLong("cache");

        collectObjectList.add(new CollectObject(containerName,"mem.size.usage", String.valueOf(Maths.div(usage,1024 * 1024)),""));
        collectObjectList.add(new CollectObject(containerName,"mem.size.cache", String.valueOf(Maths.div(cache,1024 * 1024)),""));
        collectObjectList.add(new CollectObject(containerName,"mem.usage.rate", String.valueOf(Maths.div(usage,limitMemory,5) * 100),""));
        collectObjectList.add(new CollectObject(containerName,"mem.cache.rate", String.valueOf(Maths.div(cache,limitMemory,5) * 100),""));

    }
    return collectObjectList;
}
 
Example 40
Project: Spring-Boot-Server   File: AppUserHealthRestful.java   Source Code and License 5 votes vote down vote up
/**
 * 获取太极用户健康信息
 * @return
 */
@RequestMapping(value = "/tjdata")
@ResponseBody
public PageData getUserBloodData(@RequestBody PageData pd) throws Exception {
	if(StringUtils.isBlank(pd.getString("UI_ID"))){
		return WebResult.requestFailed(10001, "参数缺失!", null);
	}else{
		String hash = HMacMD5.encrypt( pd.getString("UI_ID"), key);
		HashMap<String,String> params = new HashMap<String,String> ();
		params.put("userId", pd.getString("UI_ID"));
		params.put("bgtime", "2017-03-31");
		params.put("edtime", "2017-03-31");
		params.put("hash", hash);
		
		List<UHeader> headerList = new ArrayList<UHeader>();
		String result = HttpUtils.getPostResponse(tjUrl, params, headerList);
		result = Des.decrypt(result);
		JSONArray jobj = JSON.parseArray(result) ;
		Map resp = new HashMap();
		resp.put("UI_ID", pd.getString("UI_ID"));
		resp.put("UI_ID", pd.getString("UI_ID"));
		resp.put("HEART_BEATING", ((JSONObject)jobj.get(0)).get("pulse")==null?"0":((JSONObject)jobj.get(0)).get("pulse"));
		resp.put("DIASTOLIC_BP",  ((JSONObject)jobj.get(0)).get("dbp")==null?"0":((JSONObject)jobj.get(0)).get("dbp"));
		resp.put("SYSTOLIC_BP",((JSONObject)jobj.get(0)).get("sbp")==null?"0":((JSONObject)jobj.get(0)).get("sbp"));
		resp.put("COUNT_DATE", ((JSONObject)jobj.get(0)).get("detectionTime")==null?"0":((JSONObject)jobj.get(0)).get("detectionTime"));
		resp.put("DEVIDE_ID", ((JSONObject)jobj.get(0)).get("deviceId")==null?"0":((JSONObject)jobj.get(0)).get("deviceId"));
		return WebResult.requestSuccess(resp);
	}
}
 
Example 41
Project: DBus   File: FullPullResource.java   Source Code and License 5 votes vote down vote up
private int findDbusMessageFieldIndex(JSONObject jsonDbusMessage, String string) {
    try {
        JSONObject jsonSchema = jsonDbusMessage.getJSONObject("schema");
        JSONArray jsonFields = jsonSchema.getJSONArray("fields");
        for(int i=0;i<jsonFields.size();i++) {
            if(jsonFields.getJSONObject(i).getString("name").equals(string)) return i;
        }
    } catch (Exception e) {
        logger.error("[control message] Parsing dbusmessage to json failed, message: {}", e);
    }
    return -1;
}
 
Example 42
Project: upgradeToy   File: ParseMileage.java   Source Code and License 5 votes vote down vote up
@Test
public void test_vehicleTotalDetail() {
    File file = new File("D:\\dayData.json");
    String json = readToString(file, "UTF-8");
    JSONObject jsonObject = JSON.parseObject(json);
    JSONArray dataArray = jsonObject.getJSONArray("data");
    System.out.println(jsonObject.toJSONString());
    double result = 0;
    for (int i = 0; i < dataArray.size(); i++) {
        JSONObject temp = (JSONObject) dataArray.get(i);
        result += Double.parseDouble(temp.get("mileage").toString());
    }
    System.out.println(result);
}
 
Example 43
Project: GitHub   File: RefTest18.java   Source Code and License 5 votes vote down vote up
public void test_array() throws Exception {
    String text = "{\"b\":{},\"a\":[{\"$ref\":\"$.b\"}]}";
    
    JSONObject obj = JSON.parseObject(text);
    JSONArray array = obj.getJSONArray("a");
    Assert.assertEquals(1, array.size());
    Assert.assertNotNull(array.get(0));
}
 
Example 44
Project: ucar-weex-core   File: WXDomModule.java   Source Code and License 5 votes vote down vote up
/**
 * invoke dom method
 * @param ref
 * @param method
 * @param args
 */
public void invokeMethod(String ref, String method, JSONArray args){
  if(ref == null || method == null){
    return;
  }

  postAction(Actions.getInvokeMethod(ref,method,args),false);
}
 
Example 45
Project: UIAutomatorWD   File: ElementController.java   Source Code and License 5 votes vote down vote up
private static JSONArray getMultiElements(final BySelector sel) throws Exception {
    JSONArray res;
    List<Element> foundElements = new ArrayList<Element>();
    final List<Element> elementsFromSelector = getElements().getMultiElement(sel);
    foundElements.addAll(elementsFromSelector);
    res = elementsToJSONArray(foundElements);
    return res;
}
 
Example 46
Project: weex-uikit   File: WXDomStatement.java   Source Code and License 5 votes vote down vote up
void invokeMethod(String ref, String method, JSONArray args){
  if(mDestroy){
    return;
  }
  WXComponent comp = mWXRenderManager.getWXComponent(mInstanceId, ref);
  if(comp == null){
    WXLogUtils.e("DomStatement","target component not found.");
    return;
  }
  comp.invoke(method,args);
}
 
Example 47
Project: jboot   File: ConfigRemoteReader.java   Source Code and License 5 votes vote down vote up
/**
 * 定时扫描远程配置信息
 */
private boolean scan() {

    String listUrl = url + "/list";
    String jsonString = httpGet(listUrl);

    if (StringUtils.isBlank(jsonString)) {
        LogKit.error("can not get remote config info,plase check url : " + listUrl);
        return false;
    }

    JSONArray jsonArray = null;
    try {
        jsonArray = JSON.parseArray(jsonString);
    } catch (Throwable ex) {
        LogKit.error("can not parse json : \n" + jsonString + "\n\nfrom url : " + listUrl, ex);
        return false;
    }

    for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        curScan.put(jsonObject.getString("id"), jsonObject.getString("version"));
    }

    return true;

}
 
Example 48
Project: UIAutomatorWD   File: ActionController.java   Source Code and License 5 votes vote down vote up
private static boolean tap(JSONArray actions) throws Exception {
    for (int i = 0; i < actions.size(); i++) {
        JSONObject action = actions.getJSONObject(i);
        if(!tap(action)) {
            return false;
        }
    }
    return true;
}
 
Example 49
Project: SuitAgent   File: ScriptPlugin.java   Source Code and License 5 votes vote down vote up
private List<DetectResult.Metric> executeJSONScript(Script script,int step){
    List<DetectResult.Metric> metrics = new ArrayList<>();
    if (script != null && script.isValid()){
        try {
            String cmd = "";
            if (script.getScriptType() == ScriptType.SHELL){
                cmd = "sh " + script.getPath();
            }
            if (script.getScriptType() == ScriptType.PYTHON){
                cmd = "python " + script.getPath();
            }
            CommandUtilForUnix.ExecuteResult executeResult = CommandUtilForUnix.execWithReadTimeLimit(cmd,false,5);
            String json = executeResult.msg.trim();
            if (json.startsWith("{") && json.endsWith("}")){
                JSONObject jsonObject = JSON.parseObject(json);
                metrics.add(parseMetricFromJSONObject(jsonObject,step));
            }else if (json.startsWith("[") && json.endsWith("]")){
                JSONArray jsonArray = JSON.parseArray(json);
                if (jsonArray != null){
                    for (Object o : jsonArray) {
                        if (o instanceof JSONObject){
                            metrics.add(parseMetricFromJSONObject((JSONObject) o, step));
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("脚本执行异常",e);
        }

    }
    return metrics;
}
 
Example 50
Project: HiTSDB-Client   File: TestTagResult.java   Source Code and License 5 votes vote down vote up
@Test
public void testJSONToResult() {
    String json = "[{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1.012\"}]";

    try {
        JSONArray array = JSON.parseArray(json);
        // System.out.println(array);
        Assert.assertEquals(array.toString(),
                "[{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1\"},{\"host\":\"127.0.0.1.012\"}]");
        List<TagResult> arrayList = new ArrayList<TagResult>(array.size());

        Iterator<Object> iterator = array.iterator();
        while (iterator.hasNext()) {
            JSONObject object = (JSONObject) iterator.next();
            Set<Entry<String, Object>> entrySet = object.entrySet();
            for (Entry<String, Object> entry : entrySet) {
                String key = entry.getKey();
                Assert.assertNotEquals(key, null);
                Object valueObject = entry.getValue();
                Assert.assertNotEquals(key, null);
                String value = valueObject.toString();
                TagResult tagResult = new TagResult(key, value);
                arrayList.add(tagResult);
                break;
            }
        }
        Assert.assertEquals(arrayList.size(), 3);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
 
Example 51
Project: OftenPorter   File: SqlHandle.java   Source Code and License 5 votes vote down vote up
@Override
public JSONObject getOne(Condition query, String... keys) throws DBException
{
    JSONArray list = getJSONs(query, FIND_ONE, keys);
    Object obj = list.size() > 0 ? list.get(0) : null;
    JSONObject jsonObject = (JSONObject) obj;
    return jsonObject;
}
 
Example 52
Project: GitHub   File: Issue771.java   Source Code and License 5 votes vote down vote up
public void test_for_issue() throws Exception {
    SerializeWriter writer = new SerializeWriter(null, JSON.DEFAULT_GENERATE_FEATURE, new SerializerFeature[0]);
    int defaultBufferSize = writer.getBufferLength();
    String encoded = JSON.toJSONString(new FooBar(defaultBufferSize));
    JSONObject decoded = (JSONObject) JSON.parse(encoded);
    JSONArray dataToEncode = decoded.getJSONArray("dataToEncode"); 
    Assert.assertEquals(5, dataToEncode.size());
    writer.close();
}
 
Example 53
Project: GitHub   File: Issue955.java   Source Code and License 5 votes vote down vote up
public void test_checkArray() throws Exception {
    Art origin = makeOrigin();
    JSONObject object = (JSONObject) JSON.toJSON(origin);

    JSONArray jsonArray = new JSONArray();
    jsonArray.add(object);

    Art other = JSON.parseObject(jsonArray.getString(0), Art.class);
    assertSame(origin, other); // test passed

    other = jsonArray.getObject(0, Art.class); // return = null;
    assertSame(origin, other); // test failed
}
 
Example 54
Project: westjson   File: WestJsonCompacter.java   Source Code and License 5 votes vote down vote up
private boolean hasSameColumns(JSONArray header, JSONObject objItem) {
    if (objItem.size() != header.size()) return false;

    for (String obj : objItem.keySet())
        if (!header.contains(obj)) return false;

    return true;
}
 
Example 55
Project: ontology_setting   File: SourceController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/get-source-list", method = RequestMethod.GET)
@ResponseBody
public JSONArray getSourceList(@RequestParam(value = "type", required = false) String type) {
    logger.info(" [Http request get source list ] type = {} ", type);
    List<Source> sources;
    if (type == null || "".equals(type)) {
        sources = sourceService.getAllSource();
    } else {
        sources = sourceService.getSourcesByType(type);
    }
    JSONArray jsonArray = new JSONArray();
    for (Source source : sources) {
        JSONObject obj = new JSONObject(true);
        obj.put("key", source.getId());
        obj.put("name", source.getName());
        obj.put("type", source.getSourceType() == null ? "" : source.getSourceType().getName());
        obj.put("connection", source.getConnection());
        obj.put("sql", source.getQuery());
        obj.put("update_level", source.getUpdateLevel() == null ? "" : source.getUpdateLevel().getPeriod());
        obj.put("last_execute_time", DateUtil.format(source.getLatestExecuteTime(), "yyyy-MM-dd HH:mm:ss"));
        obj.put("valid", source.getValid());
        obj.put("creator", source.getCreator());
        obj.put("create_time", DateUtil.format(source.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        obj.put("update_time", DateUtil.format(source.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
        jsonArray.add(obj);
    }
    return jsonArray;
}
 
Example 56
Project: UIAutomatorWD   File: ActionController.java   Source Code and License 5 votes vote down vote up
private static boolean doubleTap(JSONArray actions) throws Exception {
    for (int i = 0; i < actions.size(); i++) {
        JSONObject action = actions.getJSONObject(i);
        if(!doubleTap(action)) {
            return false;
        }
    }
    return true;
}
 
Example 57
Project: GitHub   File: Issue74.java   Source Code and License 5 votes vote down vote up
public void test_for_issue() throws Exception {
    InputStream is = Issue72.class.getClassLoader().getResourceAsStream("issue74.json");
    String text = org.apache.commons.io.IOUtils.toString(is);
    is.close();
    
    JSONArray json = (JSONArray) JSON.parse(text);
    
    Assert.assertNotNull(json.getJSONObject(0).getJSONObject("dataType").getJSONObject("categoryType").getJSONArray("dataTypes").get(0));
    Assert.assertSame(json.getJSONObject(0).getJSONObject("dataType"), json.getJSONObject(0).getJSONObject("dataType").getJSONObject("categoryType").getJSONArray("dataTypes").get(0));
}
 
Example 58
Project: android-project-gallery   File: Res.java   Source Code and License 5 votes vote down vote up
/**
 * 返回列表数据, 反之返回空.
 * 
 * @return
 */
public JSONArray getDataJSONArray()
{
	if (data != null)
	{
		JSONObject jsonObject = JSONObject.parseObject(data);
		return jsonObject.getJSONArray("list");
	}

	return null;
}
 
Example 59
Project: GitHub   File: JSONPath_array_remove_0.java   Source Code and License 5 votes vote down vote up
public void test_remove() throws Exception {
    JSONObject jsonObject = new JSONObject();

    JSONArray array = new JSONArray();
    for (int i = 0; i < 10; ++i) {
        JSONObject item = new JSONObject();
        item.put("age", i);
        array.add(item);
    }
    jsonObject.put("aaa", array);

    JSONPath.remove(jsonObject, "$.aaa[0:1].age"); //解析出错
    JSONPath.remove(jsonObject, "$.aaa[0,1].age"); //解析出错
    JSONPath.remove(jsonObject, "$.aaa[0].age"); //解析正确
}
 
Example 60
Project: GitHub   File: Alipay1206.java   Source Code and License 5 votes vote down vote up
public void test_for_alipay() throws Exception {
    File file = new File("/Users/wenshao/Downloads/x.txt");
    String text = FileUtils.readFileToString(file);
    JSONObject root = JSON.parseObject(text);

    JSONObject resultObj = root.getJSONObject("resultObj");
    assertNotNull(resultObj);

    JSONArray conditionGroupItemList = resultObj.getJSONArray("conditionGroupItemList");
    assertNotNull(conditionGroupItemList);

    JSONObject conditionGroup = conditionGroupItemList.getJSONObject(0).getJSONObject("conditionGroup");
    assertNotNull(conditionGroup);

    JSONArray recordList = conditionGroup.getJSONArray("recordList");
    assertNotNull(recordList);

    JSONArray conditionItemList = recordList.getJSONObject(0).getJSONArray("conditionItemList");
    assertNotNull(conditionItemList);

    JSONObject condition = conditionItemList.getJSONObject(18).getJSONObject("condition");
    assertNotNull(condition);

    JSONArray conditionConstraint = condition.getJSONArray("conditionConstraint");
    assertNotNull(conditionConstraint);

    JSONObject constraintOptionalRecordMap = conditionConstraint.getJSONObject(0).getJSONObject("constraintOptionalRecordMap");
    assertNotNull(constraintOptionalRecordMap);

    System.out.println(constraintOptionalRecordMap);
}