双层嵌套json字符串(即json对象内嵌json数组)解析为Map

之前我层写过一篇文章,介绍了json与map的相互转化,但当时只涉及到单一的json对象或json数组,,对json对象内嵌套这json数组的json字符串无法处理,这篇文章主要解决这个问题。 之前的那篇文章址: 首先要在项目中导入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 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转换为mappublic 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 = (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*/(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());}}}

运行结果如下:

:左侧:底部:悬浮:右侧:顶部-value:3

业精于勤,荒于嬉;行成于思,毁于随。

双层嵌套json字符串(即json对象内嵌json数组)解析为Map

相关文章:

你感兴趣的文章:

标签云: