Json物件與Json字串的轉化、JSON字串與Java物件的轉換
阿新 • • 發佈:2020-10-22
相關:Json物件與Json字串的轉化、JSON字串與Java物件的轉換
本文的目的是把json串轉成map鍵值對儲存,而且只儲存葉節點的資料
比如json資料如下:
{responseHeader:{status:0,QTime:0},spellcheck:{suggestions:{中國:{numFound:9,startOffset:0,endOffset:2,suggestion:[中國工商銀行, 中國人民, 中國國際, 中國農業, 中國市場, 中國經濟, 中國人, 中國廣播, 中國文化]}},collations:{collation:中國工商銀行}}}
如果儲存在鍵值對中,變成如下:
這樣通過map,可以直接獲取對應鍵的資料。具體程式碼如下:
import org.apache.solr.client.solrj.SolrServerException;
import org.json.*;
import java.io.IOException;
import java.util.*;
/**
* @Author:sks
* @Description:
* @Date:Created in 16:18 2017/12/18
* @Modified by:
**/
public class JsontoMap {
/**
* @Author:sks
* @Description:把json物件資料儲存在map以鍵值對的形式儲存,只儲存葉節點
* @Date:
*/
private static void JsonToMap(Stack<JSONObject> stObj, Map<String, Object> resultMap) throws SolrServerException, IOException {
if(stObj == null && stObj.pop() == null){
return ;
}
JSONObject json = stObj.pop();
Iterator it = json.keys();
while(it.hasNext()){
String key = (String) it.next();
//得到value的值
Object value = json.get(key);
//System.out.println(value);
if(value instanceof JSONObject)
{
stObj.push((JSONObject)value);
//遞迴遍歷
JsonToMap(stObj,resultMap);
}
else {
resultMap.put(key, value);
}
}
}
public static void main(String []args) throws SolrServerException, IOException{
String jsonStr ="{responseHeader:{status:0,QTime:0},spellcheck:{suggestions:{中國:{numFound:9,startOffset:0,endOffset:2," +
"suggestion:[中國工商銀行, 中國人民, 中國國際, 中國農業, 中國市場, 中國經濟, 中國人, 中國廣播, 中國文化]}}," +
"collations:{collation:中國工商銀行}}}";
JSONObject obj = new JSONObject(jsonStr);
Stack<JSONObject> stObj = new Stack<JSONObject>();
stObj.push(obj);
Map<String, Object> resultMap =new HashMap<String, Object>();
JsonToMap(stObj,resultMap);
Set<String> keys = resultMap.keySet();
for (String key:keys){
System.out.println(key+":"+resultMap.get(key));
}
}
// 輸出:
// endOffset:2
// startOffset:0
// QTime:0
// numFound:9
// suggestion:["中國工商銀行","中國人民","中國國際","中國農業","中國市場","中國經濟","中國人","中國廣播","中國文化"]
// collation:中國工商銀行
// status:0
}