雙層嵌套json字串(即json對象內嵌json數組)解析為Map,jsonmap
之前我層寫過一篇文章,介紹了json與map的相互轉化,但當時只涉及到單一的json對象或json數組,對json對象內嵌套這json數組的json字串無法處理,這篇文章主要解決這個問題。
之前的那篇文章址:http://blog.csdn.net/u012116457/article/details/24371877
首先要在項目中匯入json的jar包:
在下面的代碼中處理json對象既使用了net.sf.json.JSONObject 也使用了org.json.JSONObject 兩個的包都要導。
首先在E盤下建立一個priceJson.txt,寫入一下內容:
{ "height":1, "width":1, "location":[ { "頂部":"3" },{ "底部":"1" },{ "左側":"2" },{ "右側":"1" },{ "懸浮":"4" } ], "type":[ { "1":"1" },{ "2":"2" },{ "3":"4" },{ "4":"4" } ]}
下面的類會通過read方法將檔案中的json串讀取出來,通過getMapByJson擷取到map:
package com.ngsh.common;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.HashMap;import java.util.List;import java.util.Map;import net.sf.json.JSONObject;import org.json.JSONArray;public class FileIO { //讀檔案 public String read(String path){ String data = ""; File file = new File(path); if(file.isFile()&&file.exists()){ try { InputStreamReader read = new InputStreamReader( new FileInputStream(file),"utf-8");//考慮到編碼格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while((lineTxt = bufferedReader.readLine()) != null){ data +=lineTxt; } read.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } return data; } //將json轉換為map public Map<String, Object> getMapByJson(String json) { Map<String, Object> map = new HashMap<String, Object>(); // 最外層解析 JSONObject object = object = JSONObject.fromObject(json); for (Object k : object.keySet()) { Object v = object.get(k); map.put(k.toString(), v); } Map<String, Object> map2 = new HashMap<String, Object>(); //第二層解析 第二層可能是 也可能不是 for(Map.Entry<String, Object> entry:map.entrySet()){ try { JSONArray array = new JSONArray(entry.getValue().toString()); //判斷是否是json數組 //是json數組 for (int i = 0; i < array.length(); i++) { org.json.JSONObject object2 = array.getJSONObject(i);//json數組對象 JSONObject object3 = JSONObject.fromObject(object2.toString()); //json對象 for (Object k : object3.keySet()) { Object v = object3.get(k); map2.put(k.toString(), v); } } } catch (Exception e) { //不是json串數組 map2.put(entry.getKey(), entry.getValue()); } } /* for(Map.Entry<String, Object> entry:map2.entrySet()){ System.out.println(entry.getKey()+"-"+entry.getValue()); } */ return map2; } /** * @param args */ public static void main(String[] args) { String path="E:\\priceJson.txt"; FileIO fo = new FileIO(); Map map = fo.getMapByJson(fo.read(path)); for(Map.Entry<String, Object> entry:map.entrySet()){ System.out.println("key:"+entry.getKey()+"-value:"+entry.getValue()); } }}
運行結果如下:
key:3-value:4key:2-value:2key:1-value:1key:height-value:1key:左側-value:2key:4-value:4key:width-value:1key:底部-value:1key:懸浮-value:4key:右側-value:1key:頂部-value:3
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。