Post 请求参数 数据装载. 生成JSON

本文介绍如何使用Java进行POST请求的参数封装,包括普通JSON数据、JSONArray数据以及其他数据类型的转换方法。

Post 请求参数 数据装载


一、普通JSON数据装载

Activity:

Map<String, String> map = new HashMap<String, String>();
map.put("storeCode", "12244");

request.setParams(Utils.getRequestData(mContext, map));

Util:

//获取请求参数
public static Map<String, String> getRequestData(Context mContext, Map<String, String> map){
	String requestData = JsonUtil.map2json(map);
	Map<String, String> requestMap = new HashMap<>();
	requestMap.put("requestData", requestData);
	return requestMap;
}

/**
 * Map-->Json
 * 
 * @param map
 * @return
*/
public static String map2json(Map<?, ?> map) {
	StringBuilder json = new StringBuilder();
	json.append("{");
	if (map != null && map.size() > 0) {
		for (Object key : map.keySet()) {
			json.append(object2json(key));
			json.append(":");
			json.append(object2json(map.get(key)));
			json.append(",");
		}
		json.setCharAt(json.length() - 1, '}');
	} else {
		json.append("}");
	}
	return json.toString();
}


另外一种方法:
Activity 

HashMap<String, String> params = new HashMap<String, String>();
		params.put("member_id", userItem.getName());
		params.put("member_pwd", userItem.getPassword());
		JSONObject paramsJO = Utils.mapToJSONObject(params);
		params.clear();
		params.put("requestData", paramsJO.toString());

request.setParams(params);

Utils:

/**
	 * 将HashMap转换成JSONObject
	 * 
	 * @param hm
	 * @return
	 */
public static JSONObject mapToJSONObject(HashMap hm) {
		JSONObject jsonObject = new JSONObject();
		Set set = hm.entrySet();
		java.util.Iterator it = hm.entrySet().iterator();
		while (it.hasNext()) {
			java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
			String key = (String) entry.getKey();
			Object value = entry.getValue();
			try {
				jsonObject.put(key, value);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return jsonObject;
}

二、JSONArray  参数装载,比如购物车下单。选择多个商品。

Activity :

Map<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = new JSONObject();
JSONArray product_info = new JSONArray();
	try {
		jsonObject.put("store_code", partialReceiptList.getStore_code());
		jsonObject.put("source_order_code", partialReceiptList.getSource_order_code());
		jsonObject.put("dealer_code", dealer_code);
			
		for (PartialReceiptProduct product : partialReceiptList.getProduct_info()) {
				
			JSONObject jsonObject1 = new JSONObject();
			try {
				jsonObject1.put("sku_code", product.getSku_code());
				jsonObject1.put("unit_code", product.getUnit_code());
				jsonObject1.put("amount", product.getAmount());
			} catch (JSONException e) {
				e.printStackTrace();
			}
			product_info.put(jsonObject1);
		}
		jsonObject.put("product_list", product_info);
			
			
	} catch (JSONException e) {
		e.printStackTrace();
	}
	map.clear();
	map.put("requestData", jsonObject.toString());

request.setParams(map);

三、其他数据类型转成JSON 


	/**
	 * Map-->Json
	 * 
	 * @param map
	 * @return
	 */
	public static String map2json(Map<?, ?> map) {
		StringBuilder json = new StringBuilder();
		json.append("{");
		if (map != null && map.size() > 0) {
			for (Object key : map.keySet()) {
				json.append(object2json(key));
				json.append(":");
				json.append(object2json(map.get(key)));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, '}');
		} else {
			json.append("}");
		}
		return json.toString();
	}

	/**
	 * Object-->Json
	 * 
	 * @param map
	 * @return
	 */
	public static String object2json(Object obj) {
		StringBuilder json = new StringBuilder();
		if (obj == null) {
			json.append("\"\"");
		} else if (obj instanceof String || obj instanceof Integer
				|| obj instanceof Float || obj instanceof Boolean
				|| obj instanceof Short || obj instanceof Double
				|| obj instanceof Long || obj instanceof BigDecimal
				|| obj instanceof BigInteger || obj instanceof Byte) {
			json.append("\"").append(string2json(obj.toString())).append("\"");
		} else if (obj instanceof Object[]) {
			json.append(array2json((Object[]) obj));
		} else if (obj instanceof List) {
			json.append(list2json((List<?>) obj));
		} else if (obj instanceof Map) {
			json.append(map2json((Map<?, ?>) obj));
		} else if (obj instanceof Set) {
			json.append(set2json((Set<?>) obj));
		} else {
			// json.append(bean2json(obj));
		}
		return json.toString();
	}

	/**
	 * List-->Json
	 * 
	 * @param map
	 * @return
	 */
	public static String list2json(List<?> list) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (list != null && list.size() > 0) {
			for (Object obj : list) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	/**
	 * 数组Array-->Json
	 * 
	 * @param map
	 * @return
	 */
	public static String array2json(Object[] array) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (array != null && array.length > 0) {
			for (Object obj : array) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	/**
	 * Set-->Json
	 * 
	 * @param map
	 * @return
	 */
	public static String set2json(Set<?> set) {
		StringBuilder json = new StringBuilder();
		json.append("[");
		if (set != null && set.size() > 0) {
			for (Object obj : set) {
				json.append(object2json(obj));
				json.append(",");
			}
			json.setCharAt(json.length() - 1, ']');
		} else {
			json.append("]");
		}
		return json.toString();
	}

	/**
	 * String-->Json
	 * 
	 * @param map
	 * @return
	 */
	public static String string2json(String s) {
		if (s == null)
			return "";
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < s.length(); i++) {
			char ch = s.charAt(i);
			switch (ch) {
			case '"':
				sb.append("\\\"");
				break;
			case '\\':
				sb.append("\\\\");
				break;
			case '\b':
				sb.append("\\b");
				break;
			case '\f':
				sb.append("\\f");
				break;
			case '\n':
				sb.append("\\n");
				break;
			case '\r':
				sb.append("\\r");
				break;
			case '\t':
				sb.append("\\t");
				break;
			case '/':
				sb.append("\\/");
				break;
			default:
				if (ch >= '\u0000' && ch <= '\u001F') {
					String ss = Integer.toHexString(ch);
					sb.append("\\u");
					for (int k = 0; k < 4 - ss.length(); k++) {
						sb.append('0');
					}
					sb.append(ss.toUpperCase());
				} else {
					sb.append(ch);
				}
			}
		}
		return sb.toString();
	}

1)生成 JSON:
方法 1、创建一个 map,通过构造方法将 map 转换成 json 对象
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "zhangsan");
map.put("age", 24);
JSONObject json = new JSONObject(map);


方法 2、创建一个 json 对象,通过 put 方法添加数据
JSONObject json=new JSONObject();
json.put("name", "zhangsan");
json.put("age", 24);


2)生成 JSON 数组:
创建一个 list,通过构造方法将 list 转换成 json 对象
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("name", "zhangsan");
map1.put("age", 24);
Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("name", "lisi");
map2.put("age", 25);
List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
list.add(map1);
list.add(map2);
JSONArray array=new JSONArray(list);
System.out.println(array.toString());


formcreate 表单设计 change 事件 // ================= 工具函数 ================= function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); return undefined; } // 扁平化 1 层 children(父区块 -> 子控件) function flatChildren(blocks) { const out = []; if (!Array.isArray(blocks)) return out; for (const b of blocks) { if (Array.isArray(b?.children)) { out.push(...b.children); } } return out; } // ================= 主逻辑 ================= try { // 1) 获取 parent 与 args const parent = $inject?.api?.getParentSubRule?.($inject?.self); const rawArgs = $inject?.args; const arg0 = Array.isArray(rawArgs) ? rawArgs[0] : rawArgs; const id = arg0?.id; if (!id) { console.warn('[wupinxinxi] 未获取到 args.id,跳过本次装载:', rawArgs); return; } // 可选:把 id 放到 cookie 里 document.cookie = `cpId=${id}; path=/; max-age=${60 * 60 * 24}`; // 2) 获取 TOKEN const token = getCookie('TOKEN'); if (!token) { console.warn('[wupinxinxi] 未获取到 TOKEN,未发起请求'); return; } // 3) 请求库存信息 fetch('https://mom.itwj.cn/api/Warehouse/goodsstockInfo', { method: 'POST', headers: { 'Content-Type': 'application/json', 'TOKEN': token }, body: JSON.stringify({ id }) }) .then(res => res.json()) .then(res => { const list = Array.isArray(res?.data) ? res.data : []; if (!list.length) { console.warn('[wupinxinxi] goodsstockInfo 返回空数据:', res); return; } // 4) 组装选项 const result = list.map(item => ({ value: (item?.id != null ? String(item.id) : ''), label: item?.stock_info ?? '', ck: item?.warehouse_id ?? '', cw: item?.warehouse_location_id ?? '', batch_number: item?.batch_number ?? '' })); const reslist = list.map(item => ({ value: (item?.id != null ? String(item.id) : ''), label: item?.stock_info ?? '', })); // 有些场景你们还会用到纯 value/label 数组,这里一并给出(如果不用可去掉) const options = list.map(item => ({ value: (item?.id != null ? String(item.id) : ''), label: item?.stock_info ?? '' })); // 5) 精确找到 field = 'wupinxinxi' 的控件 if (!parent || !Array.isArray(parent.children)) { console.warn('[wupinxinxi] parent 或 parent.children 不存在:', parent); return; } const children = flatChildren(parent.children); const target = children.find(c => c?.field === 'wupinxinxi'); if (!target) { console.warn("[wupinxinxi] 未找到 field='wupinxinxi' 的控件"); return; } // 6) 记录旧值,更新选项(只改 options/dic,不改 emitValue/mapOptions 等) const oldVal = target.value; // 同时写 options 与 dic 以兼容不同封装 target.options = result; target.dic = result; console.log(result,'result') console.log(reslist,'reslist') if ($inject?.api?.updateRules) { $inject.api.updateRules({ wupinxinxi: { props: { resOptions: reslist }, options:result, dic: result } }); } // 仅在未设置过 labelField/valueField 时填默认值;不要覆盖 emitValue/mapOptions target.props = { ...(target.props || {}), labelField: target?.props?.labelField ?? 'label', valueField: target?.props?.valueField ?? 'value' }; // 7) 旧值保留(仅当旧值仍存在于新选项里) const isEmit = target?.props?.emitValue === true; // true=值是纯 value;false=对象 {label,value} 等 let exists = false; if (oldVal !== undefined && oldVal !== null) { if (isEmit) { exists = result.some(o => o.value === oldVal); } else if (typeof oldVal === 'object') { exists = result.some(o => o.value === oldVal.value); } } if (oldVal !== undefined) { if (exists) { // 重新赋回,确保视图与校验同步 target.value = oldVal; } else { // 旧值不在新选项里了:按需求决定是否清空或设默认 // target.value = isEmit ? '' : null; // 或者保留不动,交给用户重新选择: // (这里选择保留不动,最稳妥) } } // 8) 如你们有 API 的“合并更新”方法,触发一次以保证响应式(可选) // if ($inject?.api?.updateRule) { // $inject.api.updateRule('wupinxinxi', { options: result, dic: result }); // } // 如果你需要把 options(纯 value/label)额外放在 props 里作为参考数据,可按需保留: // target.props.resOptions = options; // target.props._optionType = 1; }) .catch(err => { console.error('[wupinxinxi] 请求出错:', err); }); } catch (e) { console.error('[wupinxinxi] 脚本异常:', e); } 到最后获取不到options 和resoption
最新发布
08-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值