java json字符串转对象 效率_json串转自动创建java对象

java json字符串转对象 效率_json串转自动创建java对象调用方法fromJson()packagecn.enilu.flash.utils;importcn.enilu.flash.bean.entity.system.User;importcom.fasterxml.jackson.annotation.JsonInclude;importcom.fasterxml.jackson.databind.JavaType;importcom.fasterxml.jackson.databind.ObjectMapper;importja

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

调用方法fromJson()

package cn.enilu.flash.utils;

import cn.enilu.flash.bean.entity.system.User;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.StringWriter;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 封装json工具类<br>
 * 通过该类减少项目中对特定的json库依赖,方便统一切换json库,目前使用jackson
 *
 * @author :enilu
 * @date :Created in 2020/5/31 21:55
 */
public class JsonUtil {
    private static ObjectMapper objectMapper = null;

    private static ObjectMapper objectMapper() {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();
            //如果有特殊处理需求在下面做ObjectMapper的设置

        }
        return objectMapper;
    }

    public static String toJsonForHuman(Object obj) {

        try {
            return objectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String toJson(Object obj) {
        StringWriter sw = new StringWriter();

        try {
            objectMapper().writeValue(sw, obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return sw.toString();
    }

    public static String toJsonNotNull(Object obj) {
        StringWriter sw = new StringWriter();

        try {
            objectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
            objectMapper().writeValue(sw, obj);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return sw.toString();
    }

    public static <T> T fromJson(Class<T> klass, String jsonStr) {

        T obj = null;
        try {
            obj = objectMapper().readValue(jsonStr, klass);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return obj;
    }

    public static <T> List<T> fromJsonAsList(Class<T> klass, String jsonStr) {

        List<T> objList = null;
        try {
            JavaType t = objectMapper().getTypeFactory().constructParametricType(
                    List.class, klass);
            objList = objectMapper().readValue(jsonStr, t);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return objList;
    }

    /**
     * 判断给定的字符串是否是json格式
     *
     * @param jsonStr
     * @return
     */
    public static boolean isJson(String jsonStr) {
        try {
            if (jsonStr.startsWith("{")) {
                fromJson(Map.class, jsonStr);
            } else {
                fromJsonAsList(Map.class, jsonStr);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
        User user = new User();
        user.setAccount("admin");
        user.setCreateTime(new Date());

        String json = toJson(user);

        System.out.println("压缩后的json字符串:========》");
        System.out.println(json);

        System.out.println("方便调试查看的json字符串:===》");
        System.out.println(toJsonForHuman(user));

        System.out.println("不输出值为null的json字符串:==》");
        System.out.println(toJsonNotNull(user));

        User user2 = fromJson(User.class, json);

        System.out.println("json字符串转对象:==========》");
        System.out.println(user2.getAccount() + user2.getCreateTime());

        List<User> users = Lists.newArrayList(user);
        String jsons = toJson(users);
        List<User> users2 = fromJsonAsList(User.class, jsons);
        System.out.println("转换为集合后的集合长度:=======》");
        System.out.println(users2.size());

        System.out.println(isJson(json));
        System.out.println(isJson(jsons));
        System.out.println(isJson("{\"aaaa\":}"));
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/185064.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 解决Serialized class ** must implement java.io.Serializable问题「建议收藏」

    解决Serialized class ** must implement java.io.Serializable问题「建议收藏」在使用dubbo进行传递实体类时,会报错需要实现序列化问题只需在自己的model实体类里面implementsSerializable即可解决,如下packagecom.pang.back.Model;importlombok.Data;importjava.io.Serializable;@DatapublicclassUserimplementsSeria…

    2022年6月20日
    48
  • nod32 update and id

    nod32 update and idnod32update:http://u1.nod32cn.comnod32id:www.for-ever.cn/nod32转载于:https://www.cnblogs.com/stoneresearch/archive/2008/08/27/4336645.html

    2022年6月29日
    28
  • ehviewer_EhViewer(E绅士)最新版-EhViewer2021里站最新版v1.7.6-3355游戏网[通俗易懂]

    ehviewer_EhViewer(E绅士)最新版-EhViewer2021里站最新版v1.7.6-3355游戏网[通俗易懂]EhViewerapp里面有着许多的福利漫画资源哦,这里面的漫画更新的速度也是超级的快,可以让你更好的进行自己的漫画观看哦,这里面的漫画类型也是多样化的哦,每一款都是你的最爱哦,你可以在这里阅读到大量的漫画资源哦,画质也是超级的高清,这里面的漫画阅读是没有任何的广告的哦,可以让你享受到更多的漫画精彩。『EhViewer优势』1.更新速度快,每天都有新漫画资源推荐2.资源丰富,漫画类型丰富3.操作简…

    2022年7月24日
    243
  • ubuntu下vscode的使用教程_vscode连接ubuntu虚拟机

    ubuntu下vscode的使用教程_vscode连接ubuntu虚拟机1、安装ffmpegwgethttps://ffmpeg.org/releases/ffmpeg-4.1.tar.bz2tar-xjvfffmpeg-4.1.tar.bz2./configure–prefix=/usr/local/ffmpeg–enable-gpl–enable-version3–enable-nonfree–enable-postproc–enable-pthreads–enable-libfdk-aac–enable-libmp3lame

    2022年9月24日
    3
  • YUV介绍

    YUV介绍YUV表示的含义人们常用RGB表示三基色,而且RGB也可以表示出所有颜色。但视觉心理学研究表明,人眼主要是对光的感知,人的视觉系统对光的感知程度用亮度(luminance)和色度(chrominance)两个属性表示,也就是我们常说的YUV。Y就是亮度感知,而色度感知分为两个属性:色相(hue)和色饱和度(saturation)。色相也就是U,是由光波的峰值定义的,描述的是光的颜色;色饱和度V…

    2022年7月16日
    15
  • Attribute meta-data#UMENG_CHANNEL@value at AndroidManifest.xml requires a placeholder substitution b

    Attribute meta-data#UMENG_CHANNEL@value at AndroidManifest.xml requires a placeholder substitution b

    2021年10月1日
    91

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号