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

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());


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: MFC发送POST请求JSON数据,可以通过以下步骤实现: 1. 设置请求头 首先需要设置请求头,包括Content-Type和Content-Length。Content-Type设置为application/json,Content-Length设置为JSON数据的长度。 2. 创建JSON字符串 创建一个JSON字符串,可以使用CJsonObject等库来构造JSON字符串。 3. 创建连接对象 创建连接对象,使用CInternetSession::GetHttpConnection方法建立连接。 4. 发送请求 使用CHttpFile::SendRequest方法发送POST请求,并将JSON字符串作为请求内容发送出去。 5. 接收响应 使用CHttpFile::QueryInfoStatusCode获取HTTP状态码,判断请求是否成功。如果成功,使用CHttpFile::ReadString方法读取响应内容。 6. 关闭连接 使用CHttpFile::Close方法关闭连接。 以上就是MFC发送POST请求JSON数据的步骤。需要注意的是,在使用MFC发送POST请求时,需要在请求字符串中添加转义字符,以确保JSON数据能够正确传输。在发送请求前,可以通过调试工具查看请求内容,以帮助排查请求发送过程中的问题。 ### 回答2: MFC是微软的一套资源库,包含了许多封装好的类和模块,能够方便地开发Windows应用程序。而json是一种轻量级的数据交换格式,经常用于Web服务之间的数据传输。在MFC中使用Post请求发送json数据也是很常见的一种操作。 发送Post请求的方式有很多种,MFC中可以使用CInternetSession和CHttpConnection等类进行实现。首先,需要创建一个Internet会话对象,并通过该对象建立一个HTTP连接。在建立HTTP连接时,需要设置服务地址和端口号等参数。然后,可以构造一个HTTP请求,指定请求类型为POST,并将json数据填充到请求正文中。最后,通过连接对象的SendRequest方法,将HTTP请求发送给Web服务端,等待服务端响应。 具体实现可以按照以下步骤进行: 1.引入相关头文件: #include <afxinet.h> #include <afxdisp.h> #include <afxwin.h> #include <afx.h> 2.创建Internet会话对象: CInternetSession* pSession = new CInternetSession(); 3.连接Web服务: CHttpConnection * pConnect = pSession->GetHttpConnection(L"www.example.com",INTERNET_DEFAULT_HTTP_PORT,NULL,NULL); 4.构造HTTP请求: CString strUrl = L"/api/data"; CHttpFile* pFile = pConnect->OpenRequest(CHttpConnection::HTTP_VERB_POST,strUrl); 5.设置请求头信息: pFile->AddRequestHeaders(L"Content-Type: application/json"); 6.构造json数据: CString strJsonData = L"{\"key\":\"value\"}"; 7.设置请求正文: pFile->SendRequestEx(strJsonData,len,strPostData.GetLength()); 8.等待服务端响应: CString strResponse; pFile->ReadString(strResponse); 9.关闭连接: pFile->Close(); delete pConnect; delete pFile; 10.释放会话对象: delete pSession; 以上就是在MFC中发送Post请求json数据的方法。在实际开发中,还需要根据具体情况进行调整和优化。 ### 回答3: MFC(Microsoft Foundation Class)是微软公司开发的一组类库,用于在Windows操作系统上开发图形用户界面程序。MFC常用于开发Windows桌面应用程序,它提供了一套面向对象的框架,让开发过程更加高效、方便。 在MFC中发送POST请求并传输JSON数据可以通过以下步骤实现: 1. 首先,需要使用CInternetSession对象建立一个Internet会话。 ``` CInternetSession session(_T("MySession")); ``` 2. 接着,需要通过CInternetSession对象创建一个HttpConnect连接并指定服务器信息和端口号。 ``` CHttpConnection* pHttpConnect = session.GetHttpConnection(_T("localhost"), INTERNET_DEFAULT_HTTP_PORT); ``` 3. 创建一个HttpPost请求并设置请求头和请求体,请求体可以使用JSON格式进行传输。 ``` CString strRequest = _T("name=John&age=20"); CString strHeaders = _T("Content-Type: application/json\r\n"); CHttpFile* pHttpFile = pHttpConnect->OpenRequest(CHttpConnection::HTTP_VERB_POST, _T("/api/example"), nullptr, 1, nullptr, nullptr, INTERNET_FLAG_RELOAD); pHttpFile->AddRequestHeaders(strHeaders); pHttpFile->SendRequest(strRequest, strRequest.GetLength()); ``` 4. 发送HttpPost请求,并获取服务器返回的响应结果。 ``` CString strResponse; DWORD dwBytesRead = 0; CHAR buff[1024] = { 0 }; while (dwBytesRead = pHttpFile->Read(buff, 1024)) { strResponse += buff; } pHttpFile->Close(); pHttpConnect->Close(); session.Close(); ``` 通过以上方法可以完成在MFC中发送POST请求并传输JSON数据的操作。需要注意的是,请求头中需要设置Content-Type为application/json,同时请求体中的数据必须是JSON格式的字符串。此外,还需要注意HttpConnect连接、HttpPost请求和HttpFile对象的生命周期问题,确保在使用后及时进行关闭和销毁。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值