詳解Java實現(xiàn)JSONArray轉(zhuǎn)Map的三種實現(xiàn)方式
本文只是自己常用的三種,自己總結(jié)一下,不是只有這三種,杠精走開;
JSONArray數(shù)據(jù)
[
{
"flagType": 1,
"flagIcon": "1.jpg"
},
{
"flagType": 2,
"flagIcon": "2.jpg"
},
{
"flagType": 3,
"flagIcon": "3.jpg"
},
{
"flagType": 4,
"flagIcon": "4.jpg"
}
]
要轉(zhuǎn)成目標數(shù)據(jù)
{
1:"1.jpg",
2:"2.jpg",
3:"3.jpg",
4:"4.jpg"
}
第一種
JSONArray jsonArray= new JSONArray();
//填充初始數(shù)據(jù),此處過程省略
List<JSONObject> jsonObjectList = jsonArray.toJavaList(JSONObject.class);
Map<Integer, String> map = jsonObjectList.stream().filter(Objects::nonNull).collect(Collectors.toMap(item -> item.getInteger("flagType"), item -> item.getString("flagIcon")));
第二種
JSONArray jsonArray= new JSONArray();
//填充初始數(shù)據(jù),此處過程省略
Map<Integer, String> map = jsonArray.stream().filter(Objects::nonNull)
.collect(Collectors.toMap(
object -> {
JSONObject item = (JSONObject) object;
return item.getInteger("flagType");
},
object -> {
JSONObject item = (JSONObject) object;
return item.getString("flagIcon");
}
));
第三種
Map<Integer, String> flagIconMap = new HashMap<>();
JSONArray jsonArray= new JSONArray();
//填充初始數(shù)據(jù),此處過程省略
if (jsonArray != null && !jsonArray.isEmpty()) {
jsonArray.forEach(object -> {
if (object == null) {
return;
}
JSONObject jsonObject = (JSONObject) object;
if (jsonObject.getInteger("flagType") == null) {
return;
}
flagIconMap.put(jsonObject.getInteger("flagType"),jsonObject.getString("flagIcon"));
});
}
到此這篇關(guān)于詳解Java實現(xiàn)JSONArray轉(zhuǎn)Map的三種實現(xiàn)方式的文章就介紹到這了,更多相關(guān)Java JSONArray轉(zhuǎn)Map內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA-SpringBoot項目Debug啟動不了(卡住不動)的原因分析
這篇文章主要介紹了IDEA-SpringBoot項目Debug啟動不了(卡住不動)的原因分析,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
org.slf4j.Logger中info()方法的使用詳解
這篇文章主要介紹了org.slf4j.Logger中info()方法的使用詳解,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
java學生成績管理系統(tǒng)設(shè)計與實現(xiàn)
這篇文章主要介紹了java學生成績管理系統(tǒng)設(shè)計與實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01
Java實現(xiàn)EasyCaptcha圖形驗證碼的具體使用
Java圖形驗證碼,支持gif、中文、算術(shù)等類型,可用于Java Web、JavaSE等項目,下面就跟隨小編一起來了解一下2021-08-08

