• 总结的一些json格式和对象/String/Map/List等的互转工具类


     总结的一些json格式和对象/String/Map/List等的互转工具类,有需要的可以看看,需要引入jackson-core-asl-1.7.1.jar、jackson-jaxrs-1.7.1.jar、jackson-mapper-asl-1.7.1.jar这三个jar包

    1. package com.zuidaima.util.json;  
    2. import java.io.InputStream;  
    3. import java.io.OutputStream;  
    4. import java.io.Reader;  
    5. import java.io.Writer;  
    6. import java.net.URL;  
    7. import java.util.ArrayList;  
    8. import java.util.Date;  
    9. import java.util.HashMap;  
    10. import java.util.List;  
    11. import java.util.Map;  
    12.   
    13. import org.codehaus.jackson.JsonNode;  
    14. import org.codehaus.jackson.map.DeserializationConfig;  
    15. import org.codehaus.jackson.map.ObjectMapper;  
    16. import org.codehaus.jackson.map.annotate.JsonSerialize;  
    17. import org.codehaus.jackson.map.type.TypeFactory;  
    18.   
    19. public class JsonUtil {  
    20.   
    21.     private static ObjectMapper mapper = new ObjectMapper();  
    22.     static{  
    23.   
    24.         /** 
    25.          * 反序列化时忽略多余的属性 
    26.          */  
    27.         mapper.getDeserializationConfig().set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);  
    28.           
    29.         /** 
    30.          * 忽略Null的值,节省空间. 
    31.          */  
    32.         mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);  
    33.         /** 
    34.          * 忽略Default值木有变化的属性,更节省空间,用于接收方有相同的Class 
    35.          * 如int属性初始值为0,那么这个属性将不会被序列化 
    36.          */  
    37.         mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);  
    38.     }  
    39.     /** 
    40.      *  
    41.      * @Title: isJSON  
    42.      * @author kaka   
    43.      * @Description: 判断 jsonString是否可以转换成json格式 
    44.      * @param @param jsonString 
    45.      * @param @return     
    46.      * @return boolean    
    47.      * @throws 
    48.      */  
    49.     public static boolean isJSON(String jsonString) {  
    50.         return mapper.canSerialize(HashMap.class);  
    51.     }  
    52.   
    53.     public static <V> Map<String, V> toMap(String content,Class<? extends V> clazz) throws Exception {  
    54.         return mapper.readValue(content, TypeFactory.mapType(HashMap.class,String.class, clazz));  
    55.     }  
    56.   
    57.     public static <V> Map<String, V> toMap(InputStream is,Class<? extends V> clazz) throws Exception {  
    58.         return mapper.readValue(is, TypeFactory.mapType(HashMap.class,String.class, clazz));  
    59.     }  
    60.   
    61.     public static <V> Map<String, V> toMap(Reader is, Class<? extends V> clazz)throws Exception {  
    62.         return mapper.readValue(is, TypeFactory.mapType(HashMap.class,String.class, clazz));  
    63.     }  
    64.   
    65.     public static <V> Map<String, V> toMap(URL is, Class<? extends V> clazz)throws Exception {  
    66.         return mapper.readValue(is, TypeFactory.mapType(HashMap.class,String.class, clazz));  
    67.     }  
    68.   
    69.   
    70.     public static <E> List<E> toList(String content, Class<? extends E> clazz)throws Exception {  
    71.         return jsonToList(content, clazz);  
    72.     }  
    73.       
    74.     /** 
    75.      *  
    76.      * @Title: jsonToList  
    77.      * @author kaka   
    78.      * @Description: json转list , List的元素类型,会一并转换完成 如List<User> 
    79.      * @param @param <E> 
    80.      * @param @param content 
    81.      * @param @param clazz 
    82.      * @param @return 元素类型为E的List 
    83.      * @param @throws Exception     
    84.      * @return List<E>    
    85.      * @throws 
    86.      */  
    87.     public static <E> List<E> jsonToList(String content,Class<? extends E> clazz) throws Exception {  
    88.         return mapper.readValue(content, TypeFactory.collectionType(ArrayList.class, clazz));  
    89.     }  
    90.     /** 
    91.      *  
    92.      * @Title: jsonToIntArray  
    93.      * @author kaka   
    94.      * @Description: json转整形数组  
    95.      * @param @param content 
    96.      * @param @return 
    97.      * @param @throws Exception     
    98.      * @return Integer[]    
    99.      * @throws 
    100.      */  
    101.     public static Integer[] jsonToIntArray(String content) throws Exception {  
    102.         return jsonToArray(content, Integer.class);  
    103.     }  
    104.   
    105.     public static Integer[] jsonToIntArray(String content,String key) throws Exception {  
    106.         return jsonToArray(content, key, Integer.class);  
    107.     }  
    108.     /** 
    109.      *  
    110.      * @Title: jsonToArray  
    111.      * @author kaka   
    112.      * @Description: json转对象数组   
    113.      * @param @param <E> 
    114.      * @param @param content 
    115.      * @param @param clazz 数组中的对象类型 
    116.      * @param @return E类型的数组,如User[] 
    117.      * @param @throws Exception     
    118.      * @return E[]    
    119.      * @throws 
    120.      */  
    121.     public static <E> E[] jsonToArray(String content, Class<? extends E> clazz)throws Exception {  
    122.         if(content != null){  
    123.             return mapper.readValue(content, TypeFactory.arrayType(clazz));  
    124.         }else{  
    125.             return null;  
    126.         }  
    127.     }  
    128.   
    129.     /** 
    130.      *  
    131.      * @Title: fromJsonToObject  
    132.      * @author kaka   
    133.      * @Description: json转java对象,为兼容原util类 
    134.      * @param @param <T> 
    135.      * @param @param content 
    136.      * @param @param clazz 目标类型 
    137.      * @param @return 
    138.      * @param @throws Exception     
    139.      * @return T  返回类型为T的对象 
    140.      * @throws 
    141.      */  
    142.     public static <T> T fromJsonToObject(String content,Class<? extends T> clazz) throws Exception {  
    143.         return jsonToObject(content, clazz);  
    144.     }  
    145.   
    146.     public static <T> T jsonToObject(String content, Class<? extends T> clazz)throws Exception {  
    147.         return mapper.readValue(content, clazz);  
    148.     }  
    149.   
    150.     /** 
    151.      *  
    152.      * @Title: jsonToObject  
    153.      * @author kaka   
    154.      * @Description: 一个jsonStr包含多个java对象,取其中一个转化为java对象的方法   
    155.      * @param @param <T> 
    156.      * @param @param content json格式的字符串 
    157.      * @param @param key 要转换的子json串的key 
    158.      * @param @param clazz 目标类型 
    159.      * @param @return 返回类型为T的对象 
    160.      * @param @throws Exception     
    161.      * @return T    
    162.      * @throws 
    163.      */  
    164.     public static <T> T jsonToObject(String content, String key,Class<? extends T> clazz) throws Exception {  
    165.         JsonNode rootNode = mapper.readValue(content, JsonNode.class);  
    166.         JsonNode path = rootNode.path(key);  
    167.         if(!path.isMissingNode()){  
    168.             return jsonToObject(path.toString(), clazz);  
    169.         }else{  
    170.             return null;  
    171.         }  
    172.     }  
    173.       
    174.     public static Integer getInt(String content, String key) throws Exception {  
    175.         JsonNode rootNode = mapper.readValue(content, JsonNode.class);  
    176.         JsonNode path = rootNode.path(key);  
    177.         if(!path.isMissingNode()){  
    178.             return jsonToObject(path.toString(), Integer.class);  
    179.         }else{  
    180.             return null;  
    181.         }  
    182.     }  
    183.       
    184.     public static String getString(String content, String key) throws Exception {  
    185.         JsonNode rootNode = mapper.readValue(content, JsonNode.class);  
    186.         JsonNode path = rootNode.path(key);  
    187.         if(!path.isMissingNode()){  
    188.             return jsonToObject(rootNode.path(key).toString(), String.class);  
    189.         }else{  
    190.             return null;  
    191.         }  
    192.     }  
    193.       
    194.     public static Date getDate(String content, String key) throws Exception {  
    195.         JsonNode rootNode = mapper.readValue(content, JsonNode.class);  
    196.         JsonNode path = rootNode.path(key);  
    197.         if(!path.isMissingNode()){  
    198.             return jsonToObject(path.toString(), Date.class);  
    199.         }else{  
    200.             return null;  
    201.         }  
    202.     }  
    203.   
    204.     /** 
    205.      * 一个jsonStr包含多个java对象,将指定的key的json转化为对象数组的方法 
    206.      * @param content 原始的json串 
    207.      * @param key 要转换的部分 
    208.      * @param clazz 目标类型 
    209.      * @return 目标类型的对象数组 
    210.      * @throws Exception 
    211.      */  
    212.     public static <E> E[] jsonToArray(String content, String key,Class<? extends E> clazz) throws Exception {  
    213.         JsonNode rootNode = mapper.readValue(content, JsonNode.class);  
    214.         JsonNode path = rootNode.path(key);  
    215.         if(!path.isMissingNode()){  
    216.             return jsonToArray(rootNode.path(key).toString(), clazz);  
    217.         }else{  
    218.             return null;  
    219.         }  
    220.     }  
    221.       
    222.     public static Integer[] jsonToArray(String content, String key) throws Exception {  
    223.         JsonNode rootNode = mapper.readValue(content, JsonNode.class);  
    224.         JsonNode path = rootNode.path(key);  
    225.         if(!path.isMissingNode()){  
    226.             return jsonToArray(path.toString(), Integer.class);  
    227.         }else{  
    228.             return null;  
    229.         }  
    230.     }  
    231.   
    232.     /** 
    233.      *  
    234.      * @Title: jsonToList  
    235.      * @author kaka   
    236.      * @Description: 一个jsonStr包含多个java对象,将指定的key的json转化为List<E>的方法  
    237.      * @param @param <E> 
    238.      * @param @param content 原始的json串 
    239.      * @param @param key 要转换的那部分json 
    240.      * @param @param clazz 目标类型 
    241.      * @param @return 元素为目标类型的List 
    242.      * @param @throws Exception     
    243.      * @return List<E>    
    244.      * @throws 
    245.      */  
    246.     public static <E> List<E> jsonToList(String content, String key,Class<? extends E> clazz) throws Exception {  
    247.         JsonNode rootNode = mapper.readValue(content, JsonNode.class);  
    248.         JsonNode path = rootNode.path(key);  
    249.         if(!path.isMissingNode()){  
    250.             return toList(path.toString(), clazz);  
    251.         }else{  
    252.             return null;  
    253.         }  
    254.     }  
    255.   
    256.     /** 
    257.      *  
    258.      * @Title: toJson  
    259.      * @author kaka   
    260.      * @Description: 对象转化成json,已知问题 A a B b b中有a,a中有b , 如果a和b同在一个o中将不能正常转化    
    261.      * @param @param o  要转换的对象 
    262.      * @param @return json格式的字符串 
    263.      * @param @throws Exception     
    264.      * @return String    
    265.      * @throws 
    266.      */  
    267.     public static String toJson(Object o) throws Exception {  
    268.         return mapper.writeValueAsString(o);  
    269.     }  
    270.   
    271.     /** 
    272.      *  
    273.      * @Title: toJson  
    274.      * @author kaka   
    275.      * @Description: 转换成json串到out    
    276.      * @param @param out 
    277.      * @param @param o 
    278.      * @param @throws Exception     
    279.      * @return void    
    280.      * @throws 
    281.      */  
    282.     public static void toJson(OutputStream out, Object o) throws Exception {  
    283.         mapper.writeValue(out, o);  
    284.     }  
    285.   
    286.     /** 
    287.      *  
    288.      * @Title: toJson  
    289.      * @author kaka   
    290.      * @Description: 转换成json串到writer    
    291.      * @param @param out 
    292.      * @param @param o 
    293.      * @param @throws Exception     
    294.      * @return void    
    295.      * @throws 
    296.      */  
    297.     public static void toJson(Writer out, Object o) throws Exception {  
    298.         mapper.writeValue(out, o);  
    299.     }  
    300.       
    301.     public static String map2Json(Map map) throws Exception{  
    302.         return toJson(map);  
    303.     }  
    304.     /** 
    305.      *  
    306.      * @Title: formatJson  
    307.      * @author kaka   
    308.      * @Description: json字符串的格式化   
    309.      * @param @param json 
    310.      * @param @param fillStringUnit 
    311.      * @param @return     
    312.      * @return String    
    313.      * @throws 
    314.      */  
    315.     public static String formatJson(String json, String fillStringUnit) {   
    316.         if (json == null || json.trim().length() == 0) {   
    317.             return null;   
    318.         }   
    319.            
    320.         int fixedLenth = 0;   
    321.         ArrayList<String> tokenList = new ArrayList<String>();   
    322.         {   
    323.             String jsonTemp = json;   
    324.             //预读取   
    325.             while (jsonTemp.length() > 0) {   
    326.                 String token = getToken(jsonTemp);   
    327.                 jsonTemp = jsonTemp.substring(token.length());   
    328.                 token = token.trim();   
    329.                 tokenList.add(token);   
    330.             }              
    331.         }   
    332.            
    333.         for (int i = 0; i < tokenList.size(); i++) {   
    334.             String token = tokenList.get(i);   
    335.             int length = token.getBytes().length;   
    336.             if (length > fixedLenth && i < tokenList.size() - 1 && tokenList.get(i + 1).equals(":")) {   
    337.                 fixedLenth = length;   
    338.             }   
    339.         }   
    340.            
    341.         StringBuilder buf = new StringBuilder();   
    342.         int count = 0;   
    343.         for (int i = 0; i < tokenList.size(); i++) {   
    344.                
    345.             String token = tokenList.get(i);   
    346.                
    347.             if (token.equals(",")) {   
    348.                 buf.append(token);   
    349.                 doFill(buf, count, fillStringUnit);   
    350.                 continue;   
    351.             }   
    352.             if (token.equals(":")) {   
    353.                 buf.append(" ").append(token).append(" ");   
    354.                 continue;   
    355.             }   
    356.             if (token.equals("{")) {   
    357.                 String nextToken = tokenList.get(i + 1);   
    358.                 if (nextToken.equals("}")) {   
    359.                     i++;   
    360.                     buf.append("{ }");   
    361.                 } else {   
    362.                     count++;   
    363.                     buf.append(token);   
    364.                     doFill(buf, count, fillStringUnit);   
    365.                 }   
    366.                 continue;   
    367.             }   
    368.             if (token.equals("}")) {   
    369.                 count--;   
    370.                 doFill(buf, count, fillStringUnit);   
    371.                 buf.append(token);   
    372.                 continue;   
    373.             }   
    374.             if (token.equals("[")) {   
    375.                 String nextToken = tokenList.get(i + 1);   
    376.                 if (nextToken.equals("]")) {   
    377.                     i++;   
    378.                     buf.append("[ ]");   
    379.                 } else {   
    380.                     count++;   
    381.                     buf.append(token);   
    382.                     doFill(buf, count, fillStringUnit);   
    383.                 }   
    384.                 continue;   
    385.             }   
    386.             if (token.equals("]")) {   
    387.                 count--;   
    388.                 doFill(buf, count, fillStringUnit);   
    389.                 buf.append(token);   
    390.                 continue;   
    391.             }   
    392.                
    393.             buf.append(token);   
    394.             //左对齐   
    395.             if (i < tokenList.size() - 1 && tokenList.get(i + 1).equals(":")) {   
    396.                 int fillLength = fixedLenth - token.getBytes().length;   
    397.                 if (fillLength > 0) {   
    398.                     for(int j = 0; j < fillLength; j++) {   
    399.                         buf.append(" ");   
    400.                     }   
    401.                 }   
    402.             }   
    403.         }   
    404.         return buf.toString();   
    405.     }   
    406.        
    407.     private static String getToken(String json) {   
    408.         StringBuilder buf = new StringBuilder();   
    409.         boolean isInYinHao = false;   
    410.         while (json.length() > 0) {   
    411.             String token = json.substring(0, 1);   
    412.             json = json.substring(1);   
    413.                
    414.             if (!isInYinHao &&    
    415.                     (token.equals(":") || token.equals("{") || token.equals("}")    
    416.                             || token.equals("[") || token.equals("]")   
    417.                             || token.equals(","))) {   
    418.                 if (buf.toString().trim().length() == 0) {                     
    419.                     buf.append(token);   
    420.                 }   
    421.                    
    422.                 break;   
    423.             }   
    424.    
    425.             if (token.equals("\")) {   
    426.                 buf.append(token);   
    427.                 buf.append(json.substring(0, 1));   
    428.                 json = json.substring(1);   
    429.                 continue;   
    430.             }   
    431.             if (token.equals(""")) {   
    432.                 buf.append(token);   
    433.                 if (isInYinHao) {   
    434.                     break;   
    435.                 } else {   
    436.                     isInYinHao = true;   
    437.                     continue;   
    438.                 }                  
    439.             }   
    440.             buf.append(token);   
    441.         }   
    442.         return buf.toString();   
    443.     }   
    444.    
    445.     private static void doFill(StringBuilder buf, int count, String fillStringUnit) {   
    446.         buf.append(" ");   
    447.         for (int i = 0; i < count; i++) {   
    448.             buf.append(fillStringUnit);   
    449.         }   
    450.     }     
    451. }  

    引用原文:https://blog.csdn.net/springmvc_springdata/article/details/44056043

    写博客是为了记住自己容易忘记的东西,另外也是对自己工作的总结,文章可以转载,无需版权。希望尽自己的努力,做到更好,大家一起努力进步!

    如果有什么问题,欢迎大家一起探讨,代码如有问题,欢迎各位大神指正!

  • 相关阅读:
    gitea (git服务器), 修改配置,更换IP地址
    使用ffmpeg裁剪和合并视频
    linux/windows/Mac平台生成随机数的不同方法
    Android源代码同步脚本(增加设置线程参数)
    小米2S Mk6.0.1 [只能做测试体验,不能使用]
    MultiROM for the XIAOMI MI2S/2C/2! (Kexec HardBoot Enabled with Kexec HardBoot Patch!)
    [PATCH] UBUNTU: SAUCE: (no-up) apparmor: Sync to apparmor3
    [转载]起动service保存android系统log( logcat服务)
    小米2S TWRP 3.0.2-0 最新中文版本Recovery
    centos 64位编译安装 glibc-2.14
  • 原文地址:https://www.cnblogs.com/summary-2017/p/8965074.html
Copyright © 2020-2023  润新知