java解析多層嵌套json字符串問題
java分別解析下面兩個json字符串


package jansonDemo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class TestJSON {
/**
* JSON實際上也是鍵值對("key":"value")
* key 必須是字符串,value 可以是合法的 JSON 數(shù)據(jù)類型(字符串, 數(shù)字, 對象, 數(shù)組, 布爾值或 null)
* value如果是字符串,用jsonobj.getString("key")獲取
* value如果是數(shù) 字,用jsonobj.getIntValue("key"),jsonobj.getFloatValue("key"),jsonobj.getInteger("key")等基本數(shù)據(jù)類型及其包裝類的方法獲取
* value如果是布爾值,用jsonobj.getBoolean("key"),jsonobj.getBooleanValue("key")獲取
* value如果是數(shù) 組,用jsonobj.getJSONArray("key")獲取
* value如果是Object對象,用jsonobj.get("key"),獲取
* value如果是JSONObject對象,用jsonobj.getJSONObject("key")獲取
*/
/**
* 該方法用于將已有的json字符串轉換為json對象,并取出該對象中相應的key對應的value值
* 將已有的字符串轉換成jsonobject,用JSON.parseObject(jsonStr)方法
* json中只要是{}就代表一個JSONObject,[]就代表一個JSONArray
* 獲取JSONObject對象用JSONObject jsonobject.getJSONObject("key")方法
* 獲取JSONArray對象用JSONObject jsonobject.getJSONArray("key")方法
*/
private static void strWritedToJSONObject() {
//以下是一個json對象中嵌套一個json子對象
String myJsonObj = "{\n" +
" \"name\":\"runoob\",\n" +
" \"alexa\":10000,\n" +
" \"sites\": {\n" +
" \"site1\":\"www.runoob.com\",\n" +
" \"site2\":\"m.runoob.com\",\n" +
" \"site3\":\"c.runoob.com\"\n" +
" }\n" +
"}";
JSONObject jsonobj = JSON.parseObject(myJsonObj); //將json字符串轉換成jsonObject對象
/***獲取JSONObject中每個key對應的value值時,可以根據(jù)實際場景中想得到什么類型就分別運用不到的方法***/
System.out.println(jsonobj.get("name")); //取出name對應的value值,得到的是一個object
System.out.println(jsonobj.getString("name")); //取出name對應的value值,得到的是一個String
System.out.println(jsonobj.getIntValue("alexa")); //取出name對應的value值,得到的是一個int
System.out.println(jsonobj.get("sites")); //取出sites對應的value值,得到的是一個object
System.out.println(jsonobj.getString("sites"));
System.out.println(jsonobj.getJSONObject("sites")); //取出sites對應的value值,得到一個JSONObject子對象
System.out.println(jsonobj.getJSONObject("sites").getString("site2")); //取出嵌套的JSONObject子對象中site2對應的value值,必須用getJSONObject()先獲取JSONObject
/**
* 以下是一個json對象中包含數(shù)組,數(shù)組中又包含json子對象和子數(shù)組
*/
String myJsonObj2 = "{\n" +
" \"name\":\"網(wǎng)站\",\n" +
" \"num\":3,\n" +
" \"sites\": [\n" +
" { \"name\":\"Google\", \"info\":[ \"Android\", \"Google 搜索\", \"Google 翻譯\" ] },\n" +
" { \"name\":\"Runoob\", \"info\":[ \"菜鳥教程\", \"菜鳥工具\", \"菜鳥微信\" ] },\n" +
" { \"name\":\"Taobao\", \"info\":[ \"淘寶\", \"網(wǎng)購\" ] }\n" +
" ]\n" +
"}";
JSONObject jsonobj2 = JSON.parseObject(myJsonObj2); //將json字符串轉換成jsonObject對象
System.out.println(jsonobj2.get("sites"));
System.out.println(jsonobj2.getString("sites"));
System.out.println(jsonobj2.getJSONArray("sites")); //取出sites對應的value值,得到一個JSONOArray對象
//System.out.println(jsonobj2.getJSONObject("sites")); 不能用該方法,因為sites是一個JSONOArray對象
//取出json對象中sites對應數(shù)組中第一個json子對象的值
System.out.println(jsonobj2.getJSONArray("sites").getJSONObject(0)); //得到結果:{"name":"Google","info":["Android","Google 搜索","Google 翻譯"]}
System.out.println(jsonobj2.getJSONArray("sites").get(0));
System.out.println(jsonobj2.getJSONArray("sites").getString(0));
//取出json對象中sites對應數(shù)組中第一個json子對象下面info對應的嵌套子數(shù)組值
System.out.println(jsonobj2.getJSONArray("sites").getJSONObject(0).getJSONArray("info")); //得到結果:["Android","Google 搜索","Google 翻譯"]
//取出json對象中sites對應數(shù)組中第一個json子對象下面info對應的嵌套子數(shù)組中第二個值
System.out.println(jsonobj2.getJSONArray("sites").getJSONObject(0).getJSONArray("info").getString(1)); //得到結果:Google 搜索
//依次取出json對象中sites對應數(shù)組中的值
JSONArray array = jsonobj2.getJSONArray("sites");
getJsonArrayItem(array);
//依次取出json對象中sites對應數(shù)組中第二個json子對象下面info對應的嵌套子數(shù)組值
JSONArray arr = jsonobj2.getJSONArray("sites").getJSONObject(1).getJSONArray("info");
getJsonArrayItem(arr);
}
/**
* 手動添加對象到一個JSONObject
*/
private static void writeStrToJSONObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name","tom");
jsonObject.put("age",20);
JSONArray jsonArray = new JSONArray();
JSONObject jsonArrayObject1 = new JSONObject();
jsonArrayObject1.put("name","alibaba");
jsonArrayObject1.put("info","www.alibaba.com");
JSONObject jsonArrayObject2 = new JSONObject();
jsonArrayObject2.put("name","baidu");
jsonArrayObject2.put("info","www.baidu.com");
jsonArray.add(jsonArrayObject1);
jsonArray.add(jsonArrayObject2);
jsonObject.put("sites",jsonArray);
System.out.println(jsonObject);
}
/**
* 將字符串轉為JSONArray
*/
private static void strToJsonArray() {
String arrayStr = "[\n" +
" {\n" +
" \"name\":\"alibaba\",\n" +
" \"info\":\"www.alibaba.com\"\n" +
" },\n" +
" {\n" +
" \"name\":\"baidu\",\n" +
" \"info\":\"www.baidu.com\"\n" +
" }\n" +
" ]";
JSONArray array = JSON.parseArray(arrayStr);
System.out.println(array);
}
/**
* 依次取出JSONArray中的值
*/
private static void getJsonArrayItem(JSONArray array) {
for (int i=0; i<array.size(); i++) {
System.out.println(array.get(i));
}
}
//測試類
public static void main(String[] args) {
strWritedToJSONObject();
//writeStrToJSONObject();
//strToJsonArray();
}
}
嵌套(任意層)JSON解析轉換為Map
最近需要檢驗系統(tǒng)多次返回的json結果是否相同,以保證系統(tǒng)升級后的功能一致,所以產(chǎn)生了編寫json轉換程序的需求。
由于小弟編程能力尚淺,有些特殊情況的轉換沒能考慮好,希望各位可以提出,或者貼出更完善的解析程序供大家分享,先在此處拋磚引玉了。
以下程序用于把多層嵌套的json字符串轉換為平層的Map,以方便在后續(xù)的測試程序中對比結果。
源代碼
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;
import java.util.Map.Entry;
/**
* Created by chenyuzhi on 17-8-12.
*/
public class JsonParseUtil {
public static String checkFormat(String str){
String _str = str.trim();
if(_str.startsWith("[") && _str.endsWith("]")){
return _str.substring(1,_str.length()-1);
}
return _str;
}
/**
* 打印Map中的數(shù)據(jù)
* @param map
*/
public static void printJsonMap(Map map){
Set entrySet = map.entrySet();
Iterator<Map.Entry<String, Object>> it = entrySet.iterator();
//最外層提取
while(it.hasNext()){
Map.Entry<String, Object> e = it.next();
System.out.println("Key 值:"+e.getKey()+" Value 值:"+e.getValue());
}
}
/**
* JSON 類型的字符串轉換成 Map
*/
public static void parseJSON2Map(Map jsonMap,String jsonStr,String parentKey){
//字符串轉換成JSON對象
JSONObject json = JSONObject.fromObject(jsonStr);
//最外層JSON解析
for(Object k : json.keySet()){
//JSONObject 實際上相當于一個Map集合,所以我們可以通過Key值獲取Value
Object v = json.get(k);
//構造一個包含上層keyName的完整keyName
String fullKey = (null == parentKey || parentKey.trim().equals("") ? k.toString() : parentKey + "." + k);
if(v instanceof JSONArray){
//如果內(nèi)層還是數(shù)組的話,繼續(xù)解析
Iterator it = ((JSONArray) v).iterator();
while(it.hasNext()){
JSONObject json2 = (JSONObject)it.next();
parseJSON2Map(jsonMap,json2.toString(),fullKey);
}
} else if(isNested(v)){
parseJSON2Map(jsonMap,v.toString(),fullKey);
}
else{
jsonMap.put(fullKey, v);
}
}
}
public static boolean isNested(Object jsonObj){
return jsonObj.toString().contains("{");
}
public static void println(Object str){
System.out.println(str);
}
}
測試程序:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.*;
import java.util.Map.Entry;
/**
?* Created by chenyuzhi on 17-8-12.
?*/
public class JsonParseUtil {
? ? public static void main(String[] args) throws Exception {
? ? ? ? JsonParseUtil jsonParseUtil = new JsonParseUtil();
? ? ? ? jsonParseUtil.test();
? ? }
? ? public void test(){
? ? ? ? //JSON類型的字符串
? ? ? ? String strJson = "{a:1,b:2,c:3,d:[{a1:11,a2:22,a3:33},{a1:{a2:222,a3:333}}]}";
? ? ? ? Map jsonMap = new HashMap();
? ? ? ? parseJSON2Map(jsonMap,checkFormat(strJson),null);
? ? ? ? printJsonMap(jsonMap);
? ? }
}測試結果:
Key 值:a Value 值:1
Key 值:b Value 值:2
Key 值:d.a3 Value 值:33
Key 值:c Value 值:3
Key 值:d.a1 Value 值:11
Key 值:d.a2 Value 值:22
Key 值:d.a1.a3 Value 值:333
Key 值:d.a1.a2 Value 值:222
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring Boot集成Druid數(shù)據(jù)庫連接池
這篇文章主要介紹了Spring Boot集成Druid數(shù)據(jù)庫連接池,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04
在Spring Boot中實現(xiàn)多環(huán)境配置的方法
在SpringBoot中,實現(xiàn)多環(huán)境配置是一項重要且常用的功能,它允許開發(fā)者為不同的運行環(huán)境,這種方式簡化了環(huán)境切換的復雜度,提高了項目的可維護性和靈活性,本文給大家介紹在Spring Boot中實現(xiàn)多環(huán)境配置的方法,感興趣的朋友跟隨小編一起看看吧2024-09-09
springboot如何開啟一個監(jiān)聽線程執(zhí)行任務
這篇文章主要介紹了springboot如何開啟一個監(jiān)聽線程執(zhí)行任務問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
spring?和?idea?建議不要使用?@Autowired注解的原因解析
@Autowired?是Spring框架的注解,而@Resource是JavaEE的注解,這篇文章主要介紹了spring和idea建議不要使用@Autowired注解的相關知識,需要的朋友可以參考下2023-11-11

