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 }
  • 相关阅读:
    Socket网络通信之数据传递
    多线程中join()的用法
    JAVA多线程实现的三种方式
    通过读取配置文件,启动mongodb
    利用ajax获取网页表单数据,并存储到数据库之二(使用SSH)
    利用ajax获取网页表单数据,并存储到数据库之一(使用JDBC)
    Null reference pointer was passed to the stub when not debugging with IE
    代码生成了解
    Linq to sql 入门
    SharePoint 2013 入门
  • 原文地址:https://www.cnblogs.com/a757956132/p/5368397.html
Copyright © 2011-2022 走看看