java小工具util系列3:JSON转实体类对象工具

在这里插入图片描述

文章目录

  • 准备工作
    • 1.JSONObject获取所有的key
    • 2.集合中实体对象转换 list中Enrey转Dto
    • 3.字符串转List<BusyTimeIndicatorAlarmThreshold>
    • 4.json字符串转JSONObject
    • 5.list根据ids数组过滤list
    • 6.json字符串转JavaBean对象
    • 7.json对象转javabean
    • 8.jsonObject转map
    • 9.List\<User>转jsonArray
    • 10.jsonArray转成String[]
    • 问题:为啥使用int就判断失效,而使用Integer和String都能准确判断?
  • 本人其他文章链接

准备工作

引入pom

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.78</version>
</dependency>
    
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.22</version>
 </dependency>    

实体bean

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    //姓名
    private String name;
}

1.JSONObject获取所有的key

技巧:
JSONObject获取key:↓
	JSONObject obj;
	for (Map.Entry<String, Object> entry : cutReceiveAlarmMessageObject.entrySet()) {
           String s = entry.getKey();
    }

2.集合中实体对象转换 list中Enrey转Dto

list中EnreyDto:↓
	List<WarningNoticeDto> warningNoticeDtoList = warningNoticeList.getInfo().getList().stream().map(this::getEntryToDto).collect(Collectors.toList());
	/**
     * entry转DTO
     * @param warningNotice entry
     * @return dto
     */
    private WarningNoticeDto getEntryToDto(WarningNotice warningNotice) {
        WarningNoticeDto warningNoticeDto = new WarningNoticeDto();
        BeanUtils.copyProperties(warningNotice, warningNoticeDto);
        return warningNoticeDto;
    }

3.字符串转List

import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.JSONObject;

String str = "[
  {
    "id": 5,
    "nodeIdArr": "[\"221\",\"222\"]",
    "nodeNameArr": "[\"enb_221\",\"2222\"]",
    "upperLimitOfTheBusyTimeThreshold": 9,
    "lowerLimitOfTheBusyTimeThreshold": 2,
    "dateRangeBeginTime": 1701648000000,
    "dateRangeEndTime": 1701682200000,
    "createTime": 1701676594000,
    "updateTime": 1701737385000,
    "activeState": "1"
  },
  {
    "id": 6,
    "nodeIdArr": "[\"2003\",\"501\",\"10010\"]",
    "nodeNameArr": "[\"CityA\",\"501\",\"Vir1\"]",
    "upperLimitOfTheBusyTimeThreshold": 9,
    "lowerLimitOfTheBusyTimeThreshold": 2,
    "dateRangeBeginTime": 1701648000000,
    "dateRangeEndTime": 1701682200000,
    "createTime": 1701676641000,
    "updateTime": 1701737382000,
    "activeState": "1"
  }]"
List<BusyTimeIndicatorAlarmThreshold> busyTimeIndicatorAlarmThresholdList = new ArrayList<>();
busyTimeIndicatorAlarmThresholdList = JSONObject.parseObject(str, new TypeReference<List<BusyTimeIndicatorAlarmThreshold>>() {});

方式一、List busyTimeIndicatorAlarmThresholdList = new ArrayList<>();
busyTimeIndicatorAlarmThresholdList = JSONObject.parseObject(str, new TypeReference<List>() {});

方式二、List userList = JSONArray.parseArray(str, User.class);

4.json字符串转JSONObject

@Test
public void jsonStrConverJSONObject(){
    String str = "{\"id\":1,\"name\":\"tom\"}";
    JSONObject jsonObject = JSONObject.parseObject(str);
    System.out.println(jsonObject);     
}

输出:{“name”:“tom”,“id”:1}

5.list根据ids数组过滤list

@Test
public void listFilter() {
    List<User> list = new ArrayList<>();
    list.add(new User(1, "a"));
    list.add(new User(2, "b"));
    list.add(new User(3, "c"));
    list.add(new User(4, "d"));
    list.add(new User(5, "e"));
    list.add(new User(6, "f"));
    list.add(new User(7, "g"));
    list.add(new User(8, "h"));
    list.add(new User(9, "i"));
    list.add(new User(10, "j"));

    //注意:数组类型必须使用Integer才可以,使用int会判断失败
    Integer[] arr = new Integer[]{1,2,5,6,9};
    List<User> filterList = list.stream().filter(item -> Arrays.asList(arr).contains(item.getId())).collect(Collectors.toList());
    filterList.stream().forEach(System.out::println);
}

6.json字符串转JavaBean对象

@Test
public void jsonStrConverBean(){
    String str = "{\"id\":1,\"name\":\"tom\"}";
    User user = JSONObject.parseObject(str, User.class);
    System.out.println(user);   
}

输出:User(id=1, name=tom)

7.json对象转javabean

@Test
public void JSONObjectConverBean(){
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("id", 1);
    jsonObject.put("name", "tom");
    User user = JSONObject.toJavaObject(jsonObject, User.class);
    System.out.println(user);   
}

输出:User(id=1, name=tom)

8.jsonObject转map

@Test
public void JSONObjectConverMap(){
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("id", 1);
    jsonObject.put("name", "tom");
    Map<String,String> map = JSONObject.parseObject(jsonObject.toJSONString(), Map.class);
    System.out.println(map);   
}

输出:{name=tom, id=1}

9.List<User>转jsonArray

@Test
public void listConverjJsonArray(){
    List<User> list = new ArrayList<>();
    list.add(new User(1, "a"));
    list.add(new User(2, "b"));
    //错误写法,因为list.toString()输出[User(id=1, name=a), User(id=2, name=b)]。这东西无法json解析,会报错:com.alibaba.fastjson.JSONException: syntax error, pos 2, line 1, column 3[User(id=1, name=a), User(id=2, name=b)]
    //        JSONArray jsonArray =JSONArray.parseArray(list.toString());
    //正确写法,简写方式
    JSONArray jsonArray =JSONArray.parseArray(JSONObject.toJSONString(list));

    //正确写法,复杂方式
    //        JSONArray jsonArray = new JSONArray();
    //        JSONObject jsonObject = null;
    //        for (User user: list) {
    //            jsonObject = new JSONObject();
    //            jsonObject.put("id", user.getId());
    //            jsonObject.put("name", user.getName());
    //            jsonArray.add(jsonObject);
    //        }
    System.out.println(jsonArray);
}

10.jsonArray转成String[]

@Test
public void jsonArrayConverStringArray(){
    JSONArray jsonArray = new JSONArray();
    jsonArray.add(0, "100");
    jsonArray.add(1, "101");
    jsonArray.add(2, "102");
    System.out.println("jsonArray:" + jsonArray);

    String[] stringArr = new String[jsonArray.size()];
    for (int i = 0; i < jsonArray.size(); i++) {
        stringArr[i] = jsonArray.get(i).toString();
    }
    for(String str : stringArr) {
        System.out.println(str);
    }
}

问题:为啥使用int就判断失效,而使用Integer和String都能准确判断?

/**
  * 问题:为啥使用int就判断失效,而使用Integer和String都能准确判断?
  * 答案:不能将基本数据类型转化为List列表。
*/
@Test
public void test1() {
    int[] arr = new int[]{1,2,5,6,9};
    System.out.println(Arrays.asList(arr).contains(1)); //结果为false
    Integer[] arr2 = new Integer[]{1,2,5,6,9};
    System.out.println(Arrays.asList(arr2).contains(1)); //结果为true
    String[] arr3 = new String[]{"1","2","5","6","9"};
    System.out.println(Arrays.asList(arr3).contains("1")); //结果为true

    //验证答案如下,把arr、arr2、arr3分别返回查看返回泛型,能够看出Arrays.asList(arr)返回的居然是List<int[]>,问题就出在这,说明list里面包含的是一个个的int[],用这个判断ints.contains(1),肯定为false
    List<int[]> ints = Arrays.asList(arr);
    List<Integer> integers = Arrays.asList(arr2);
    List<String> strings = Arrays.asList(arr3);
}

本人其他文章链接

1.java小工具util系列1:日期毫秒数转日期字符串
https://blog.csdn.net/a924382407/article/details/121955349

2.java小工具util系列2:获取字符modelStr在字符串str中第count次出现时的下标
https://blog.csdn.net/a924382407/article/details/121955455

3.java小工具util系列3:正则表达式匹配:匹配不包含@特殊字符的字符串
https://blog.csdn.net/a924382407/article/details/121955737

4.java小工具util系列4:String[] 转 List< Integer >
https://blog.csdn.net/a924382407/article/details/121956201

5.java小工具util系列5:基础工具代码(Msg、PageResult、Response、常量、枚举)
https://blog.csdn.net/a924382407/article/details/120952865

6.java小工具util系列6:java执行string返回boolean结果
https://blog.csdn.net/a924382407/article/details/117124536

7.java小工具util系列7:集合中实体对象转换 list中Enrey转Dto
https://blog.csdn.net/a924382407/article/details/121957545

8.java小工具util系列8:JSONObject获取key
https://blog.csdn.net/a924382407/article/details/121957607

9.java小工具util系列9:检测一个字符串是否是时间格式
https://blog.csdn.net/a924382407/article/details/123948881

10.java小工具util系列10:时间毫秒数、时间格式字符串、日期之间相互转化
https://blog.csdn.net/a924382407/article/details/124581851

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/221499.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

IDEA中,光标移动快捷键(Shift + 滚轮前后滚动:当前文件的横向滚动轴滚动。)

除此之外&#xff0c;其他常用的光标移动快捷键包括&#xff1a; Shift 滚轮前后滚动&#xff1a;当前文件的横向滚动轴滚动。Shiftenter&#xff1a;快速将鼠标移动到下一行。Ctrl ]&#xff1a;移动光标到当前所在代码的花括号结束位置。Ctrl 左方向键&#xff1a;光标跳转…

IDEA插件配置--maven篇

仓库地址 IDEA中maven插件仓库默认地址&#xff1a;C:\Users\Administrator.m2\repository 在D盘新建一个文件夹用做本地仓库地址&#xff0c;例如 D:\Program Files\maven\repository&#xff0c;将原先C盘路径下的repository拷贝到D盘 修改settings.xml配置文件 镜像地…

基于微服务架构的外卖系统源码开发

在当前互联网时代&#xff0c;外卖行业蓬勃发展&#xff0c;用户对于高效、智能的外卖服务需求不断增加。为了满足这一需求&#xff0c;采用微服务架构的外卖系统成为了开发的主流方向。本文将探讨基于微服务的外卖系统源码开发&#xff0c;涉及到关键技术和示例代码。 1. 微…

SpringBoot3-快速体验

1、pom.xml <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apache.org/POM/4.0.…

搞笑视频无水印下载,高清无水印视频网站!

搞笑视频无水印下载这件事情一直困扰了广大网友&#xff0c;每当看见好玩好笑的搞笑视频然而下载下来的时候&#xff0c;要么画质模糊就带有水印今天分享大家几个搞笑视频无水印下载方法。 这是一个非常良心的搞笑视频无水印下载小程序水印云&#xff0c;它支持图片去水印、视…

Flutter桌面应用程序定义系统托盘Tray

文章目录 概念实现方案1. tray_manager依赖库支持平台实现步骤 2. system_tray依赖库支持平台实现步骤 3. 两种方案对比4. 注意事项5. 话题拓展 概念 系统托盘&#xff1a;系统托盘是一种用户界面元素&#xff0c;通常出现在操作系统的任务栏或桌面顶部。它是一个水平的狭长区…

vscode git管理

vscode添加了git管理 1、如下按钮&#xff0c;可以看到本次的修改部分 2、安装git history 就可以查看每次的不同部分了

阿里云环境下的配置DNS和SLB的几种实践示例

一、背景 对于大多中小型公司来说&#xff0c;生产环境大多是购买阿里云或者腾讯云等等&#xff0c;也就存在以下需求&#xff1a; 外网域名内网域名SLB容器化部署 特别是前两项&#xff0c;一定是跳不过的。容器化部署&#xff0c;现在非K8S莫属了。 既然是购买阿里云&…

Codeforces Round 913 (Div. 3)(A~G)

1、编程模拟 2、栈模拟 3、找规律&#xff1f;&#xff08;从终止状态思考&#xff09; 4、二分 5、找规律&#xff0c;数学题 6、贪心&#xff08;思维题&#xff09; 7、基环树 A - Rook 题意&#xff1a; 直接模拟 // Problem: A. Rook // Contest: Codeforces - C…

JSON 语法详解:轻松掌握数据结构(上)

&#x1f90d; 前端开发工程师&#xff08;主业&#xff09;、技术博主&#xff08;副业&#xff09;、已过CET6 &#x1f368; 阿珊和她的猫_CSDN个人主页 &#x1f560; 牛客高级专题作者、在牛客打造高质量专栏《前端面试必备》 &#x1f35a; 蓝桥云课签约作者、已在蓝桥云…

人、机不同在于变与多

人擅长变&#xff0c;如变模态、变尺度&#xff0c;而机器侧重多&#xff0c;如多模态、多尺度。 人类擅长变化的能力是由于我们的大脑和思维能力的灵活性所决定的。我们可以通过学习和适应&#xff0c;改变我们的态度、行为方式和观点&#xff0c;以适应不同的情境和环境。例如…

python基于轻量级卷积神经网络模型ShuffleNetv2开发构建辣椒病虫害图像识别系统

轻量级识别模型在我们前面的博文中已经有过很多实践了&#xff0c;感兴趣的话可以自行移步阅读&#xff1a; 《移动端轻量级模型开发谁更胜一筹&#xff0c;efficientnet、mobilenetv2、mobilenetv3、ghostnet、mnasnet、shufflenetv2驾驶危险行为识别模型对比开发测试》 《基…

Python实现FA萤火虫优化算法优化卷积神经网络回归模型(CNN回归算法)项目实战

说明&#xff1a;这是一个机器学习实战项目&#xff08;附带数据代码文档视频讲解&#xff09;&#xff0c;如需数据代码文档视频讲解可以直接到文章最后获取。 1.项目背景 萤火虫算法&#xff08;Fire-fly algorithm&#xff0c;FA&#xff09;由剑桥大学Yang于2009年提出 , …

dockerdesktop 制作asp.net core webapi镜像-连接sqlserver数据库容器

1.使用visual studio 创建 asp.net core webapi项目 选择启用docker 会生成Dockerfile文件 2.使用efcore连接数据库&#xff0c;安装efcore的包 <ItemGroup><PackageReference Include"Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version&qu…

MySQL 对null 值的特殊处理

需求 需要将不再有效范围内的所有数据都删除&#xff0c;所以用not in (有效list)去实现&#xff0c;但是发现库里&#xff0c;这一列为null的值并没有删除&#xff0c;突然想到是不是跟 anull 不能生效一样&#xff0c;not in 对null不生效&#xff0c;也需要特殊处理。 解决 …

西安安泰Aigtek——ATA-8152射频功率放大器

ATA-8152射频功率放大器简介 ATA-8152是一款射频功率放大器。其P1dB输出功率100W&#xff0c;饱和输出功率200W。增益数控可调&#xff0c;一键保存设置&#xff0c;提供了方便简洁的操作选择&#xff0c;可与主流的信号发生器配套使用&#xff0c;实现射频信号的放大。宽范围供…

数据结构 | 查漏补缺之

DFS&BFS 哈希表-二次探测再散列法 完全二叉树&深度计算 排序 快速排序-挖坑法 插入、选择、冒泡、区别 插入从第一个元素开始&#xff0c;后面的元素与前面以及排序好的元素比较&#xff0c;插入其中&#xff0c;使其有序&#xff0c;最终效果是前面的有序选择选择…

dockerdesktop推送镜像到dockerhub

1.查看镜像(打开powershell) docker ps2.打tag docker tag pengzx/aspnetcoredocker:v1 pengzx/aspnetcoredocker:v2pengzx/aspnetcoredocker:v1:本地的镜像名加版本号 pengzx/aspnetcoredocker:v2&#xff1a;需要上传的镜像名&#xff08;要以dockerhub的用户名开头/本地镜像…

Hadoop学习笔记(HDP)-Part.14 安装YARN+MR

目录 Part.01 关于HDP Part.02 核心组件原理 Part.03 资源规划 Part.04 基础环境配置 Part.05 Yum源配置 Part.06 安装OracleJDK Part.07 安装MySQL Part.08 部署Ambari集群 Part.09 安装OpenLDAP Part.10 创建集群 Part.11 安装Kerberos Part.12 安装HDFS Part.13 安装Ranger …

根文件系统的开机自启动测试

一. 简介 本文在之前制作的根文件系统可以正常运行的基础上进行的&#xff0c;继上一篇文章地址如下&#xff1a; 完善根文件系统-CSDN博客 在前面测试软件hello 运行时&#xff0c;都是等 Linux 启动进入根文件系统以后手动输入 “./hello” 命令 来完成的。 我们一般做好产…