import java.util.HashMap
import java.util.Iterator
import java.util.Map
import net.sf.json.JSONObject
public Map<String, String>toMap(Object object)
{Map<String, String>data = new HashMap<String, String>()
// 将json字符樱带串脊拦芦转换成jsonObject
JSONObject jsonObject = JSONObject.fromObject(object)
Iterator ite = jsonObject.keys()
while (ite.hasNext())
{String key = ite.next().toString()
衡冲
String value = jsonObject.get(key).toString()
data.put(key, value)
// 或者直接将 jsonObject赋值给Map
// data = jsonObject
return data
}
我们薯衫芹数毕需要先把json字符串转化为net.sf.json.JSONObject对象,java中这样就可以完成json字符串到Map的转换了。
1.将数组转换塌世为JSON:String[] arr = {"asd","dfgd","asd","234"}JSONArray jsonarray = JSONArray.fromObject(arr)System.out.println(jsonarray)
2.对象转换成JSON:UserInfo user = new UserInfo(1001,"张三")JSONArray jsonArray = JSONArray.fromObject(user)System.out.println( jsonArray )
3.把Map转换成json, 要使用jsonObject对象:Map<String, Object>map = new HashMap<String, Object>()map.put("userId", 1001)map.put("userName", "张三")map.put("userSex", "男")JSONObject jsonObject = JSONObject.fromObject(map)System.out.println(jsonObject)
4.把List转换成JSON数据:List<UserInfo>list = new ArrayList<UserInfo>()UserInfo user = new UserInfo(1001, "张三")list.add(user)list.add(user)list.add(user)JSONArray jsonArray = JSONArray.fromObject(list)System.out.println(jsonArray)
5.
方法,整个json串是一个神尺list<map>或者Map,然后Map中又可以添加Map,也可以添加List<Map>,如此层层添加即可。因此,只使用List和Map *** 作,就可以拼接任意固定格式的Json字符串。
java代码:
String inputJson = ""巧数Map inputMap = new HashMap()
// userMap userMap = new HashMap()userMap.put("loginName", "))userMap.put("loginPassword","))inputMap.put("userInfo", userMap)
// dataMap bussdataMap = new HashMap()bussdataMap.put("tableName", "")List<Map>dataList = new ArrayList<Map>游宽高()Map dataMap = new HashMap()
// dataMap.put("id", "")dataMap.put("id_card_no","" )dataList.add(dataMap)bussdataMap.put("row", dataList)inputMap.put("dataInfo", bussdataMap)
// operationTypeinputMap.put("operate", "插入")JSONWriter writer = new JSONWriter(false)inputJson = writer.write(inputMap)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)