jsonUtil

本文介绍了一个用于处理JSON数据的工具类,该类基于Jackson库实现了对象与JSON字符串的互相转换,并提供了美观打印功能。文章详细展示了如何配置ObjectMapper来确保序列化和反序列化的准确性,同时提供了一些示例代码来说明如何使用这些方法。
package com.mmall.util;


import com.google.common.collect.Lists;
import com.mmall.pojo.Category;
import com.mmall.pojo.TestPojo;
import com.mmall.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by blus
 */
@Slf4j
public class JsonUtil {


    private static ObjectMapper objectMapper = new ObjectMapper();
    static{
        //对象的所有字段全部列入
        objectMapper.setSerializationInclusion(Inclusion.ALWAYS);


        //取消默认转换timestamps形式
        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,false);


        //忽略空Bean转json的错误
        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);


        //所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss
        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));


        //忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
    }






    public static <T> String obj2String(T obj){
        if(obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String)obj :  objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse Object to String error",e);
            return null;
        }
    }


    public static <T> String obj2StringPretty(T obj){
        if(obj == null){
            return null;
        }
        try {
            return obj instanceof String ? (String)obj :  objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("Parse Object to String error",e);
            return null;
        }
    }










    public static <T> T string2Obj(String str,Class<T> clazz){
        if(StringUtils.isEmpty(str) || clazz == null){
            return null;
        }


        try {
            return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz);
        } catch (Exception e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }





  // new typeReference<List<User>>
    public static <T> T string2Obj(String str, TypeReference<T> typeReference){
        if(StringUtils.isEmpty(str) || typeReference == null){
            return null;
        }
        try {
            return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));
        } catch (Exception e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }




    public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);
        try {
            return objectMapper.readValue(str,javaType);
        } catch (Exception e) {
            log.warn("Parse String to Object error",e);
            return null;
        }
    }






















    public static void main(String[] args) {
        TestPojo testPojo = new TestPojo();
        testPojo.setName("Geely");
        testPojo.setId(666);


        //{"name":"Geely","id":666}
        String json = "{\"name\":\"Geely\",\"color\":\"blue\",\"id\":666}";
        TestPojo testPojoObject = JsonUtil.string2Obj(json,TestPojo.class);
//        String testPojoJson = JsonUtil.obj2String(testPojo);
//        log.info("testPojoJson:{}",testPojoJson);


        log.info("end");


//        User user = new User();
//        user.setId(2);
//        user.setEmail("geely@happymmall.com");
//        user.setCreateTime(new Date());
//        String userJsonPretty = JsonUtil.obj2StringPretty(user);
//        log.info("userJson:{}",userJsonPretty);




//        User u2 = new User();
//        u2.setId(2);
//        u2.setEmail("geelyu2@happymmall.com");
//
//
//
//        String user1Json = JsonUtil.obj2String(u1);
//
//        String user1JsonPretty = JsonUtil.obj2StringPretty(u1);
//
//        log.info("user1Json:{}",user1Json);
//
//        log.info("user1JsonPretty:{}",user1JsonPretty);
//
//
//        User user = JsonUtil.string2Obj(user1Json,User.class);
//
//
//        List<User> userList = Lists.newArrayList();
//        userList.add(u1);
//        userList.add(u2);
//
//        String userListStr = JsonUtil.obj2StringPretty(userList);
//
//        log.info("==================");
//
//        log.info(userListStr);
//
//
//        List<User> userListObj1 = JsonUtil.string2Obj(userListStr, new TypeReference<List<User>>() {
//        });
//
//
//        List<User> userListObj2 = JsonUtil.string2Obj(userListStr,List.class,User.class);


        System.out.println("end");


    }










}
在 Java 中,将对象转换为 JSON 字符串可以使用 `JSONUtil.toJsonStr()` 方法,该方法属于 Hutool 工具库的一部分。此方法会将 Java 对象序列化为 JSON 字符串,并且默认情况下不会包含值为 `null` 的属性,从而避免生成冗余的 JSON 数据,使结果更加简洁[^1]。 例如,可以将一个实体类对象转换为 JSON 字符串: ```java import cn.hutool.json.JSONUtil; public class Example { public static void main(String[] args) { GxyJobEntity gxyJobEntity = new GxyJobEntity(); gxyJobEntity.setUserId("user001"); gxyJobEntity.setPlanId("plan001"); gxyJobEntity.setStudentId("stu001"); String jsonStr = JSONUtil.toJsonStr(gxyJobEntity); System.out.println(jsonStr); } } ``` 在上述代码中,`GxyJobEntity` 是一个自定义的 Java Bean,`JSONUtil.toJsonStr()` 将其转换为 JSON 字符串。如果某些字段的值为 `null`,则这些字段将不会出现在最终的 JSON 字符串中[^1]。 此外,也可以将 `List` 类型的数据转换为 JSON 字符串: ```java import cn.hutool.json.JSONUtil; import java.util.ArrayList; import java.util.List; public class ListToJsonExample { public static void main(String[] args) { List<GxyJobEntity> voList = new ArrayList<>(); GxyJobEntity entity1 = new GxyJobEntity(); entity1.setUserId("user001"); entity1.setPlanId("plan001"); entity1.setStudentId("stu001"); voList.add(entity1); String jsonStr = JSONUtil.toJsonStr(voList); System.out.println(jsonStr); } } ``` 如果需要控制序列化行为,例如包含 `null` 值的字段,可以通过 `JSONConfig` 类进行配置。默认情况下,`JSONUtil.toJsonStr()` 使用的是不包含 `null` 值的配置,但可以通过自定义配置来改变这一行为[^1]。 对于更复杂的场景,例如需要将 JSON 字符串还原为 Java 对象时,可以使用 `JSONUtil.toBean()` 方法: ```java String driverDtoStr = "{\"userId\":\"user001\",\"planId\":\"plan001\",\"studentId\":\"stu001\"}"; GxyJobEntity driverDto = JSONUtil.toBean(driverDtoStr, GxyJobEntity.class); System.out.println(driverDto); ``` 通过这种方式,可以灵活地在 Java 对象和 JSON 字符串之间进行转换,适用于多种数据处理和传输场景[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值