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

java小工具util系列3:JSON转实体类对象工具_第1张图片

文章目录

  • 准备工作
    • 1.JSONObject获取所有的key
    • 2.集合中实体对象转换 list中Enrey转Dto
    • 3.字符串转List
    • 4.json字符串转JSONObject
    • 5.list根据ids数组过滤list
    • 6.json字符串转JavaBean对象
    • 7.json对象转javabean
    • 8.jsonObject转map
    • 9.List\转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 busyTimeIndicatorAlarmThresholdList = new ArrayList<>();
busyTimeIndicatorAlarmThresholdList = JSONObject.parseObject(str, new TypeReference>() {});

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

方式二、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转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,问题就出在这,说明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

你可能感兴趣的:(JAVA相关,java,json,json转实体类,jsonarray)