好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

详解Java实现JSONArray转Map的三种实现方式

本文只是自己常用的三种,自己总结一下,不是只有这三种,杠精走开;

JSONArray数据

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

[

     {

         "flagType" : 1,

         "flagIcon" : "1.jpg"

     },

     {

         "flagType" : 2,

         "flagIcon" : "2.jpg"

     },

     {

         "flagType" : 3,

         "flagIcon" : "3.jpg"

     },

     {

         "flagType" : 4,

         "flagIcon" : "4.jpg"

     }

]

要转成目标数据

?

1

2

3

4

5

6

{

     1: "1.jpg" ,

     2: "2.jpg" ,

     3: "3.jpg" ,

     4: "4.jpg"

}

 第一种

?

1

2

3

4

JSONArray jsonArray= new JSONArray();

//填充初始数据,此处过程省略

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" )));

第二种 

?

1

2

3

4

5

6

7

8

9

10

11

12

13

JSONArray jsonArray= new JSONArray();

//填充初始数据,此处过程省略

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" );

                         }

                 ));

第三种 

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

Map<Integer, String> flagIconMap = new HashMap<>();

 

JSONArray jsonArray= new JSONArray();

//填充初始数据,此处过程省略

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" ));

     });

}

到此这篇关于详解Java实现JSONArray转Map的三种实现方式的文章就介绍到这了,更多相关Java JSONArray转Map内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/weixin_43075027/article/details/109533803

查看更多关于详解Java实现JSONArray转Map的三种实现方式的详细内容...

  阅读:29次