zoukankan      html  css  js  c++  java
  • jsonUtil 工具类

     1 package org.konghao.basic.util;
     2 
     3 import java.io.IOException;
     4 import java.io.StringWriter;
     5 
     6 import com.fasterxml.jackson.core.JsonFactory;
     7 import com.fasterxml.jackson.core.JsonGenerator;
     8 import com.fasterxml.jackson.core.JsonParseException;
     9 import com.fasterxml.jackson.databind.JsonMappingException;
    10 import com.fasterxml.jackson.databind.ObjectMapper;
    11 
    12 public class JsonUtil {
    13     private static JsonUtil ju;
    14     private static JsonFactory jf;
    15     private static ObjectMapper mapper;
    16 
    17     private JsonUtil() {
    18     }
    19 
    20     public static JsonUtil getInstance() {
    21         if (ju == null)
    22             ju = new JsonUtil();
    23         return ju;
    24     }
    25 
    26     public static ObjectMapper getMapper() {
    27         if (mapper == null) {
    28             mapper = new ObjectMapper();
    29         }
    30         return mapper;
    31     }
    32 
    33     public static JsonFactory getFactory() {
    34         if (jf == null)
    35             jf = new JsonFactory();
    36         return jf;
    37     }
    38 
    39     public String obj2json(Object obj) {
    40         JsonGenerator jg = null;
    41         try {
    42             jf = getFactory();
    43             mapper = getMapper();
    44             StringWriter out = new StringWriter();
    45             jg = jf.createJsonGenerator(out);
    46             mapper.writeValue(jg, obj);
    47             return out.toString();
    48         } catch (IOException e) {
    49             e.printStackTrace();
    50         } finally {
    51             try {
    52                 if (jg != null)
    53                     jg.close();
    54             } catch (IOException e) {
    55                 e.printStackTrace();
    56             }
    57         }
    58         return null;
    59     }
    60 
    61     public Object json2obj(String json, Class<?> clz) {
    62         try {
    63             mapper = getMapper();
    64             return mapper.readValue(json, clz);
    65         } catch (JsonParseException e) {
    66             e.printStackTrace();
    67         } catch (JsonMappingException e) {
    68             e.printStackTrace();
    69         } catch (IOException e) {
    70             e.printStackTrace();
    71         }
    72         return null;
    73     }
    74 
    75 
    76 }
  • 相关阅读:
    redis(lettuce)
    Dubbo与SSM整合(认证授权)步骤
    maven常用命令
    Dubbo(RPC框架)
    SpringCache
    mybatis(SSM整合)
    java设计模式-命令模式
    java设计模式-原型模式
    java设计模式-职责链模式
    java设计模式-建造者模式
  • 原文地址:https://www.cnblogs.com/a757956132/p/5368397.html
Copyright © 2011-2022 走看看