Java 列表json格式的字符串转列表对象 并遍历取值

[{
	"roleModel": {
		"roleId": 27,
		"roleCode": "role_analyst",
		"roleName": "分析师"
	},
	"workspaceName": "营销组",
	"workspaceId": "asgaeqwesd-123asdqw"
}, {
	"roleModel": {
		"roleId": 27,
		"roleCode": "role_workspace_analyst",
		"roleName": "分析师"
	},
	"workspaceName": "管理组",
	"workspaceId": "aaaase123-1"
}]

具体方法

1.转列表对象

导入依赖与包

  
            cn.hutool
            hutool-all
            5.8.0.M2
import cn.hutool.json.JSONUtil;

String s ="[{
	"roleModel": {
		"roleId": 27,
		"roleCode": "role_analyst",
		"roleName": "分析师"
	},
	"workspaceName": "营销组",
	"workspaceId": "asgaeqwesd-123asdqw"
}, {
	"roleModel": {
		"roleId": 27,
		"roleCode": "role_workspace_analyst",
		"roleName": "分析师"
	},
	"workspaceName": "管理组",
	"workspaceId": "aaaase123-1"
}]"


List list = JSONUtil.parseArray(s);

for (Object o : list) {System.out.println(o);}
 
  

最后输出的数据;

{
	"roleModel": {
		"roleId": 27,
		"roleCode": "role_analyst",
		"roleName": "分析师"
	},
	"workspaceName": "营销组",
	"workspaceId": "asgaeqwesd-123asdqw"
} 
{
	"roleModel": {
		"roleId": 27,
		"roleCode": "role_workspace_analyst",
		"roleName": "分析师"
	},
	"workspaceName": "管理组",
	"workspaceId": "aaaase123-1"
}

2.遍历取值;object获取属性值

        List list = JSONUtil.parseArray(s);

        List workSpaceIds=new ArrayList<>();
        for (Object o : list) {
            Map entity = (Map)o;
            workSpaceIds.add(entity.get("workspaceId").toString());
        }
        for(int i=0;i 
  

你可能感兴趣的:(java,前端,服务器)