首页 前端知识 Java工具类-JSON转实体类对象工具(可复制)

Java工具类-JSON转实体类对象工具(可复制)

2024-07-01 23:07:42 前端知识 前端哥 997 177 我要收藏

准备工作

引入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中Enrey转Dto:↓
	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);   
}

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

转载请注明出处或者链接地址:https://www.qianduange.cn//article/13756.html
标签
评论
发布的文章

json基本格式

2024-07-08 09:07:01

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!