溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

java項(xiàng)目中如何實(shí)現(xiàn)將JSONObject轉(zhuǎn)為HashMap

發(fā)布時(shí)間:2020-11-16 14:36:11 來源:億速云 閱讀:2555 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)java項(xiàng)目中如何實(shí)現(xiàn)將JSONObject轉(zhuǎn)為HashMap,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

1.首先要導(dǎo)入json相關(guān)的jar包
引入的jar包:
(版本自行定義,可以選用使用人數(shù)偏多的版本,這樣比較穩(wěn)定)
commons-beanutils-1.9.2.jar
commons-collections-3.2.1.jar
commons-lang-2.6.jar
commons-logging-1.2.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar

jar包的下載可以去下面這個(gè)網(wǎng)址搜索:
https://mvnrepository.com/

java項(xiàng)目中如何實(shí)現(xiàn)將JSONObject轉(zhuǎn)為HashMap

2.在Eclipse下(也可以是IntelliJ IDEA或者M(jìn)yEclipse)
新建package和Class(步驟略過,可自行選擇名字),這里就使用jsonTest。

以下代碼塊方法見注釋,是將JSONObject轉(zhuǎn)換為HashMap的主要方法,傳入?yún)?shù)為一個(gè)JSONObject對(duì)象,返還值為一個(gè)HashMap。

//1.將JSONObject對(duì)象轉(zhuǎn)換為HashMap<String,String>
public static HashMap<String, String> JsonObjectToHashMap(JSONObject jsonObj){
	HashMap<String, String> data = new HashMap<String, String>(); 
	Iterator it = jsonObj.keys();
	while(it.hasNext()){
		String key = String.valueOf(it.next().toString());
		String value = (String)jsonObj.get(key).toString();
		data.put(key, value);
	}
	System.out.println(data);
	return data;
}

這個(gè)方法是將JSON字符串轉(zhuǎn)換為HashMap,傳入?yún)?shù)為一段json格式的字符串,返還一個(gè)HashMap。

//2.將json字符串轉(zhuǎn)換成HashMap<String,String>
public static HashMap<String, String> JsonToHashMap(String JsonStrin){	
	HashMap<String, String> data = new HashMap<String, String>(); 
	try{
	  // 將json字符串轉(zhuǎn)換成jsonObject 
	  JSONObject jsonObject = JSONObject.fromObject(JsonStrin); 
	  @SuppressWarnings("rawtypes")
		Iterator it = jsonObject.keys();
	  // 遍歷jsonObject數(shù)據(jù),添加到Map對(duì)象 
	  while (it.hasNext()) 
	  {
	  	String key = String.valueOf(it.next()).toString(); 
	    String value = (String) jsonObject.get(key).toString();  
	    data.put(key, value); 
	  } 
	}catch (Exception e) {
		e.printStackTrace();
		//JOptionPane.showMessageDialog(null,"ERROR:["+e+"]");
	}
	System.out.println(data);
	return data; 	
}	

在這里順便介紹一下Iterator類(迭代器)
迭代器是一種設(shè)計(jì)模式,它是一個(gè)對(duì)象,它可以遍歷并選擇序列中的對(duì)象,而開發(fā)人員不需要了解該序列的底層結(jié)構(gòu)。迭代器通常被稱為“輕量級(jí)”對(duì)象,因?yàn)閯?chuàng)建它的代價(jià)小。
  Java中的Iterator功能比較簡單,并且只能單向移動(dòng):
  (1) 使用方法iterator()要求容器返回一個(gè)Iterator。第一次調(diào)用Iterator的next()方法時(shí),它返回序列的第一個(gè)元素。注意:iterator()方法是java.lang.Iterable接口,被Collection繼承。
  (2) 使用next()獲得序列中的下一個(gè)元素。
  (3) 使用hasNext()檢查序列中是否還有元素。
  (4) 使用remove()將迭代器新返回的元素刪除。
  Iterator是Java迭代器最簡單的實(shí)現(xiàn),為List設(shè)計(jì)的ListIterator具有更多的功能,它可以從兩個(gè)方向遍歷List,也可以從List中插入和刪除元素。

3.直接上代碼

package JSON;

import java.util.HashMap;
import java.util.Iterator;
import net.sf.json.JSONObject;

public class JsonTest {

	public static void main(String[] args) {
		JSONObject jsonObj = new JSONObject(true);
		String content1 = "aaaaa";
		String content2 = "bbbbb";
		String content3 = "ccccc";
		jsonObj.put("a", content1);
		jsonObj.put("b", content2);
		jsonObj.put("c", content3);
		System.out.println(jsonObj.toString());
		JsonObjectToHashMap(jsonObj);
		String jsonstr = "{name:'王楊',sex:'男',school:'鄭州航空工業(yè)管理學(xué)院'}";
		JsonToHashMap(jsonstr);
	}
	
	//1.將JSONObject對(duì)象轉(zhuǎn)換為HashMap<String,String>
	public static HashMap<String, String> JsonObjectToHashMap(JSONObject jsonObj){
		HashMap<String, String> data = new HashMap<String, String>(); 
		Iterator it = jsonObj.keys();
		while(it.hasNext()){
			String key = String.valueOf(it.next().toString());
			String value = (String)jsonObj.get(key).toString();
			data.put(key, value);
		}
		System.out.println(data);
		return data;
	}
	//2.將json字符串轉(zhuǎn)換成HashMap<String,String>
	public static HashMap<String, String> JsonToHashMap(String JsonStrin){	
		HashMap<String, String> data = new HashMap<String, String>(); 
		try{
		  // 將json字符串轉(zhuǎn)換成jsonObject 
		  JSONObject jsonObject = JSONObject.fromObject(JsonStrin); 
		  @SuppressWarnings("rawtypes")
			Iterator it = jsonObject.keys();
		  // 遍歷jsonObject數(shù)據(jù),添加到Map對(duì)象 
		  while (it.hasNext()) 
		  {
		  	String key = String.valueOf(it.next()).toString(); 
		    String value = (String) jsonObject.get(key).toString();  
		    data.put(key, value); 
		  } 
		}catch (Exception e) {
			e.printStackTrace();
			//JOptionPane.showMessageDialog(null,"ERROR:["+e+"]");
		}
		System.out.println(data);
		return data; 	
	}	

}

記得修改自己的package名稱和 class名稱。

4.調(diào)用main方法測試
(1)傳入?yún)?shù)為JSONObject:

java項(xiàng)目中如何實(shí)現(xiàn)將JSONObject轉(zhuǎn)為HashMap

輸出結(jié)果為:

java項(xiàng)目中如何實(shí)現(xiàn)將JSONObject轉(zhuǎn)為HashMap

(2)傳入?yún)?shù)為JSON字符串:

java項(xiàng)目中如何實(shí)現(xiàn)將JSONObject轉(zhuǎn)為HashMap

輸出結(jié)果為:

java項(xiàng)目中如何實(shí)現(xiàn)將JSONObject轉(zhuǎn)為HashMap

這里可以看到,輸出的參數(shù)順序和傳入時(shí)正好相反。但是輸出類型為HashMap,數(shù)據(jù)存儲(chǔ)的格式是以key-value鍵值對(duì)的形式存數(shù)于HashMap中的。我們可以通過獲取key值來獲取到其對(duì)應(yīng)的value。
增加如下代碼在main方法最后面:

System.out.println("");//空格換行
//通過對(duì)應(yīng)的key鍵值,獲取value
HashMap<String,String> hashmap = JsonToHashMap(jsonstr);
System.out.println("--------通過遍歷HashMap輸出值:-------");
System.out.println("name:"+hashmap.get("name")+",sex:"+
hashmap.get("sex")+",school:"+hashmap.get("school"));

得到如下結(jié)果:

java項(xiàng)目中如何實(shí)現(xiàn)將JSONObject轉(zhuǎn)為HashMap

結(jié)語:

到此基本的方法介紹完畢,其實(shí)是依靠了JSONObject這個(gè)對(duì)象的fromObject()方法。fromObject()方法可以轉(zhuǎn)換的類型很多,可以是map、list、數(shù)組等等。運(yùn)用在自己的項(xiàng)目中時(shí),可以是bean或者model等自定義的類。

1. List集合轉(zhuǎn)換成json代碼
List list = new ArrayList();
list.add( "first" );
list.add( "second" );
JSONArray jsonArray2 = JSONArray.fromObject( list );

2. Map集合轉(zhuǎn)換成json代碼
Map map = new HashMap();
map.put("name", "json");
map.put("bool", Boolean.TRUE);
map.put("int", new Integer(1));
map.put("arr", new String[] { "a", "b" });
map.put("func", "function(i){ return this.arr[i]; }");
JSONObject json = JSONObject.fromObject(map);

3. Bean轉(zhuǎn)換成json代碼
JSONObject jsonObject = JSONObject.fromObject(new JsonBean());

4. 數(shù)組轉(zhuǎn)換成json代碼
boolean[] boolArray = new boolean[] { true, false, true };
JSONArray jsonArray1 = JSONArray.fromObject(boolArray);

以上類型均可以借用fromObject()方法轉(zhuǎn)換為一個(gè)JSONObject類型實(shí)例。
json作為輕量級(jí)的數(shù)據(jù)格式,在前后端數(shù)據(jù)交互時(shí)很常見,每個(gè)公司應(yīng)該都有自己的JSON轉(zhuǎn)換方法,是公司常見的工具類。
方便了隨后的開發(fā)使用。

關(guān)于java項(xiàng)目中如何實(shí)現(xiàn)將JSONObject轉(zhuǎn)為HashMap就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI