/** * 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; }
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)); }
@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"); }
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()); } }
@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); }
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; }
@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); }
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; }
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(); } }
/** * 不匹配 <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; }
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))); } }
@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); }
@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(); } }
/** * 获取所有机构列表 * @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; }
/**判断是否为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; }
@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); }
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; }
/** * 获得全部资源以及已经授权的资源的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"; }
/**获取存储信息*/ @SuppressWarnings("unchecked") public <T> List<T> getInfoMany(long memberId, String key,Class<T> clazz){ try { if(memberId != ReturnUtil.NOT_LOGIN_CODE) key += memberId; Object obj = null; if(session!=null){ obj = session.getAttribute(key); }else{ obj = JSONArray.parseArray(RedisUtil.getJedis().get(key)); } return (List<T>) obj; } catch (Exception e) { System.out.println("【获取存储信息】异常:"+e.toString()); return null; } }
@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; }
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; }
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; }
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); } }
/** * @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; }
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; }
@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); }
@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); } } } }
@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 的影响 }
private void saveCurLayout() { String aJson = JSONArray.toJSONString(SysConfig.CurLayout); try { FileUtil.writeFile(aJson, SysConfig.Catalog_Project + "cashe/curLayout.txt"); } catch (IOException e) { e.printStackTrace(); } }
/** * 用户健康信息 * @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); } } }
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); }
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(); }
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; }
/** * 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; } }
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'); } } }
/** * 验证时间格式 <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; } }
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); } } }
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; }
/** * 内存 * @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; }