1. 程式人生 > >java 提取json格式中的某一id值,拼接成字串

java 提取json格式中的某一id值,拼接成字串

1、檔案為json格式,提取某一個id的值

[{
“name”: “zhansam”,
“id”: 123
},
{
“name”: “lisi”,
“id”: 456
},
{
“name”: “wangwu”,
“id”: 789
}
]

2、

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.HashSet;
import java.util
.Map; import java.util.Scanner; import java.util.Set; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; /** * @Description: json格式轉換 * @date 2016年6月17日 下午5:03:11 */ public class testJson { public static void main(String[] args) { //讀取硬碟中json格式的檔案 String fullFileName = "E:/json.txt"
; File file = new File(fullFileName); Scanner scanner = null; StringBuilder buffer = new StringBuilder(); try { scanner = new Scanner(file, "utf-8"); while (scanner.hasNextLine()) { buffer.append(scanner.nextLine
()); } } catch (FileNotFoundException e) { e.getMessage(); } finally { if (scanner != null) { scanner.close(); } } if(buffer.toString() == null || "".equals(buffer.toString())){ System.out.println("讀取不到檔案。。。"); return ; } System.out.println("第一步,讀取e盤下面的檔案,E: "+buffer.toString()); // com.alibaba.fastjson.JSONObject 轉成json物件 System.out.println("第二步,轉成json物件 JSONObject =" + JSONObject.parseArray(buffer.toString())); JSONArray aa =JSONObject.parseArray(buffer.toString()); int len = aa.size(); System.out.println("第三步,json物件屬性長度 len= "+len); Map<String, Object> hashMap = new HashMap<String, Object>(); String iiiiids = ""; Set<String> quchong = new HashSet<String>(); //一層巢狀,第二層物件為json物件陣列 獲取所有key為id的值value for(int i=0 ;len > i ;i++){ JSONObject neibuJson =new JSONObject(); //System.out.println("neibuJson 空 "+neibuJson.parse(aa.getString(i))); JSONObject neibuJson2 =(JSONObject)neibuJson.parse(aa.getString(i)); //JSONObject neibuJson3 =(JSONObject)JSONObject.parse(aa.getString(i)); //System.out.println("第三步,每個內部物件的值 ="+neibuJson2); //System.out.println("neibuJson3"+neibuJson3); //System.out.println("第三步,json物件屬性id的值="+neibuJson.get("id")); //System.out.println("第三步,json物件屬性id的值="+neibuJson.getString("id")); Set<String> keySet = neibuJson2.keySet(); // System.out.println("第四步,內部物件的key值"+"keySet="+keySet); // System.out.println("第四步,內部物件的key對應的value值"+"keySetValue-neibuJson2="+neibuJson2.get("id")); for (String key : keySet) {//注:hashMap中,key值唯一 hashMap.put(key, neibuJson2.get(key)); } //SET集合去重 if(neibuJson2.get("id")!= null){ quchong.add(neibuJson2.get("id").toString()); } iiiiids += neibuJson2.get("id")+ ","; } System.out.println("最後需要的結果,iiiiids= "+iiiiids); System.out.println("唯一 的hashMap="+hashMap); System.out.println("去重後Set size="+quchong.size()); System.out.println("去重後Set 內容="+quchong); } }