利用BeanMap进行对象与Map的相互转换 / 利用fastjson简单实现/json去转义 + JSONObject转实体

-------------------2021-04-26追加---JSONObject的妙用(通过TypeReference定义任意转化)--------------
Map<String, Object> jsonMap = JSONObject.parseObject(paramStr);
Map<String, String> busiDataMap = JSONObject.parseObject(JSONObject.toJSONString(jsonMap.get("busiData")),new TypeReference<Map<String,String>>(){});

---------2019.2.26追加--------------将结果转化为需要的对象对其进行处理 + String或JSON转实体-----------------------------

//将结果转化为需要的对象对其进行处理
private Result<Object> rsValue2Bean(String strRsValue) {
    /* --------------多结果集----------- */
    //用JSONObject暂存结果集
    Result<Object> result = Result.createSuccessResult();
    List<JSONObject> payInfos = JSONObject.parseObject(strRsValue, List.class);
    //最终需要的结果集
    List<PayInfo> payInfosRes = Lists.newArrayList();
    //遍历处理暂存结果集
    for (JSONObject json : payInfos) {
        //将JSONObject对象转化为需要的PayInfo对象
        PayInfo payInfo = JSONObject.parseObject(JSONObject.toJSONString(json), PayInfo.class);
        //...对payInfo对象进行一系列处理...
        //将需要的对象添加到最终结果集合
        payInfosRes.add(payInfo);
    }
    result.setData(payInfosRes);

    /* --------------单个结果---------- */
    JSONObject json = JSONObject.parseObject(strRsValue, JSONObject.class);
    PayInfo payInfo = JSONObject.parseObject(JSONObject.toJSONString(json), PayInfo.class);
    result.setData(payInfo);
    
    return result;
}

---------------------------2019.1.29追加--------------json去转义 + JSONObject转实体-----------------------------

public class Test {
    public static void main(String[] args) {
        String s="[{\"tradeMode\":\"MIC\",\"accountNo\":null,\"cash\":\"1200\",\"posTransNo\":null,\"bankTransNo\":null,\"bankDate\":\"20190129\",\"bankTime\":\"120447\",\"bankSettlementTime\":null,\"bankCardNo\":\"A37318138\",\"posIndexNo\":null,\"sellerAccountNo\":null,\"transNo\":\"1135862251\",\"payAccountNo\":null,\"outTradeNo\":null,\"extend\":null}]";
        
        //去除json转义
        String tradeModeList= StringEscapeUtils.unescapeJava(s);

        List<JSONObject> payInfos = JSONObject.parseObject(tradeModeList,List.class);
        
        //JSONObject->实体
        JSONObject payInfoJson = payInfos.get(0);
        PayInfo payInfo = JSON.parseObject(JSONObject.toJSONString(payInfoJson), PayInfo.class);

        System.out.println(payInfo);
    }
}

---------------------------2018.10.25追加---------------BeanInfo与FastJson效率比较: BeanInfo效率高----------------------------

因见评论区网友提问使用BeanInfo与FastJson进行Map与Bean间转换的效率问题, 故作以测试!

结论如下: 

使用2018.4.18追加的BeanInfo方式进行转换效率高出FastJson很多倍.

(实测数据:使用BeanInfo与FastJson做相同的转化, BeanInfo方式需要时间20ms左右,而使用FastJson方式需要时间280ms左右)

---------------------------2018.4.18追加-------------------------------------------

Map与实体Bean之间互转工具类:

 

 Java Code 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

 

package com.*;


import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;


/**
 * @Description:
 * @Date:Created in 22:34 2018/4/17
 * @Modified By:
 */

public class Bean2MapUtil {

    
/**
     * Map转实体类共通方法 (Map2Bean)
     *
     * @param type
     * @param map
     * @return Object
     * @throws Exception
     */

    public static Object convertMap(Class type, Map map) throws Exception {
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        Object obj=type.newInstance();
        PropertyDescriptor[] propertyDescriptors=beanInfo.getPropertyDescriptors();
        
for (PropertyDescriptor descriptor:propertyDescriptors) {
            
String propertyName = descriptor.getName();
            
if (map.containsKey(propertyName)){
                Object value = map.get(propertyName);
                descriptor.getWriteMethod().invoke(obj,value);
            }
        }
        
return obj;
    }




    
/**
     * 实体类转Map共通方法 (Bean2Map)
     *
     * @param bean 实体类
     * @return Map
     * @throws Exception
     */

    public static Map convertBean(Object bean) throws Exception {
        Class type=bean.getClass();
        Map returnMap = 
new HashMap();
        BeanInfo beanInfo = Introspector.getBeanInfo(type);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        
for (PropertyDescriptor descriptor:propertyDescriptors) {
            
String propertyName = descriptor.getName();
            
if (!propertyName.equals("class")){
                Method readMethod = descriptor.getReadMethod();
                Object result = readMethod.invoke(bean);
                
if (result!=null){
                    returnMap.put(propertyName,result);
                }
else {
                    returnMap.put(propertyName,
"");
                }
            }
        }
        
return returnMap;
    }
}

 

 

 

---------------------------2018.4.12追加-------------------------------------------

[推荐使用该法]

总结: 利用fastjson进行简单处理.即可实现Map与Bean之间的转换.

说明: dataMap---Map集合

        RegistrationScheduleResultBO---实体类

Map->Bean 的实现:

 String jsonRegistrationScheduleResultBO = JSONObject.toJSONString(dataMap);
                     RegistrationScheduleResultBO registrationScheduleResultBO = JSONObject.parseObject(jsonRegistrationScheduleResultBO, RegistrationScheduleResultBO.class); 

 

 

---------------------------2018.4.12之前-------------------------------------------

 

利用BeanMap进行对象与Map的相互转换

参原文:点击打开链接

javabean与map的转换有很多种方式,比如:

1、通过ObjectMapper先将bean转换为json,再将json转换为map,但是这种方法比较绕,且效率很低,经测试,循环转换10000个bean,就需要12秒!!!不推荐使用

2、通过java反射,获取bean类的属性和值,再转换到map对应的键值对中,这种方法次之,但稍微有点麻烦

3、通过net.sf.cglib.beans.BeanMap类中的方法,这种方式效率极高,它跟第二种方式的区别就是因为使用了缓存,初次创建bean时需要初始化,之后就使用缓存,所以速度极快,经测试,循环bean和map的转换10000次,仅需要300毫秒左右。

 

所以,推荐第3种方式。  以下是相关代码:

 

[java] view plain copy

  1.        /** 
  2.  * 将对象装换为map 
  3.  * @param bean 
  4.  * @return 
  5.  */  
  6. public static <T> Map<String, Object> beanToMap(T bean) {  
  7.     Map<String, Object> map = Maps.newHashMap();  
  8.     if (bean != null) {  
  9.         BeanMap beanMap = BeanMap.create(bean);  
  10.         for (Object key : beanMap.keySet()) {  
  11.             map.put(key+"", beanMap.get(key));  
  12.         }             
  13.     }  
  14.     return map;  
  15. }  
  16.   
  17. /** 
  18.  * 将map装换为javabean对象 
  19.  * @param map 
  20.  * @param bean 
  21.  * @return 
  22.  */  
  23. public static <T> T mapToBean(Map<String, Object> map,T bean) {  
  24.     BeanMap beanMap = BeanMap.create(bean);  
  25.     beanMap.putAll(map);  
  26.     return bean;  
  27. }  
  28.   
  29. /** 
  30.  * 将List<T>转换为List<Map<String, Object>> 
  31.  * @param objList 
  32.  * @return 
  33.  * @throws JsonGenerationException 
  34.  * @throws JsonMappingException 
  35.  * @throws IOException 
  36.  */  
  37. public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {  
  38.     List<Map<String, Object>> list = Lists.newArrayList();  
  39.     if (objList != null && objList.size() > 0) {  
  40.         Map<String, Object> map = null;  
  41.         T bean = null;  
  42.         for (int i = 0,size = objList.size(); i < size; i++) {  
  43.             bean = objList.get(i);  
  44.             map = beanToMap(bean);  
  45.             list.add(map);  
  46.         }  
  47.     }  
  48.     return list;  
  49. }  
  50.   
  51. /** 
  52.  * 将List<Map<String,Object>>转换为List<T> 
  53.  * @param maps 
  54.  * @param clazz 
  55.  * @return 
  56.  * @throws InstantiationException 
  57.  * @throws IllegalAccessException 
  58.  */  
  59. public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps,Class<T> clazz) throws InstantiationException, IllegalAccessException {  
  60.     List<T> list = Lists.newArrayList();  
  61.     if (maps != null && maps.size() > 0) {  
  62.         Map<String, Object> map = null;  
  63.         T bean = null;  
  64.         for (int i = 0,size = maps.size(); i < size; i++) {  
  65.             map = maps.get(i);  
  66.             bean = clazz.newInstance();  
  67.             mapToBean(map, bean);  
  68.             list.add(bean);  
  69.         }  
  70.     }  
  71.     return list;  
  72. }  
  73.  
fastjson 中,字符串转义的处理主要依赖于 `JSON.toJSONString` 和 `JSON.parseObject` 方法。这些方法会自动处理 JSON 字符串中的特殊字符,例如引号、反斜杠等,并确保生成的 JSON 字符串是有效的。 ### 处理字符串转义的方式 1. **序列化时自动转义** 使用 `JSON.toJSONString` 将对象转换JSON 字符串时,fastjson 会自动对字符串中的特殊字符进行转义处理。例如,双引号 (`"`) 会被转义为 `\"`,换行符会被转义为 `\n`,制表符会被转义为 `\t` 等[^1]。 ```java String input = "Hello \"World\"\n"; String jsonStr = JSON.toJSONString(input); System.out.println(jsonStr); // 输出: "Hello \"World\"\n" ``` 2. **反序列化时自动解析转义字符** 使用 `JSON.parseObject` 或 `JSON.parseArray` 进行反序列化时,fastjson 会自动识别并还原 JSON 字符串中的转义字符。例如,`\n` 会被还原为换行符,`\"` 会被还原为双引号。 ```java String jsonStr = "\"Hello \\\\ World\""; String result = JSON.parseObject(jsonStr, String.class); System.out.println(result); // 输出: Hello \ World ``` 3. **手动处理嵌套 JSON 字符串** 在某些情况下,可能需要将一个 JSON 字符串作为另一个 JSON 对象的值。此时可以使用 `JSON.toJSONString` 对内层 JSON 字符串进行转义,以确保外层 JSON 的结构正确[^1]。 ```java HashMap<String, String> innerMap = new HashMap<>(); innerMap.put("a", "b"); innerMap.put("c", "d"); String innerJson = JSON.toJSONString(innerMap); HashMap<String, String> outerMap = new HashMap<>(); outerMap.put("aa", "ba"); outerMap.put("ca", innerJson); // 嵌套 JSON 字符串 String outerJson = JSON.toJSONString(outerMap); System.out.println(outerJson); // 输出: {"aa":"ba","ca":"{\"a\":\"b\",\"c\":\"d\"}"} ``` 4. **解析嵌套 JSON 字符串** 如果 JSON 字符串中包含嵌套的 JSON 字符串,可以通过两次解析来获取内部的 JSON 数据[^1]。 ```java String outerJson = "{\"aa\":\"ba\",\"ca\":\"{\\\"a\\\":\\\"b\\\",\\\"c\\\":\\\"d\\\"}\"}"; JSONObject outerObj = JSON.parseObject(outerJson); String innerJson = outerObj.getString("ca"); JSONObject innerObj = JSON.parseObject(innerJson); System.out.println(innerObj); // 输出: {"a":"b","c":"d"} ``` 5. **禁用转义功能(可选)** 如果希望生成的 JSON 字符串不包含任何转义字符,可以使用 `SerializerFeature` 参数控制输出格式。 ```java String rawJson = JSON.toJSONString(input, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue); ``` --- ### 示例代码总结 以下是一个完整的示例,演示了如何在 fastjson 中处理字符串转义: ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.util.HashMap; public class FastJsonEscapeExample { public static void main(String[] args) { // 创建内层 HashMap HashMap<String, String> innerMap = new HashMap<>(); innerMap.put("a", "b"); innerMap.put("c", "d"); // 序列化为 JSON 字符串(内层) String innerJson = JSON.toJSONString(innerMap); // 创建外层 HashMap 并嵌套内层 JSON 字符串 HashMap<String, String> outerMap = new HashMap<>(); outerMap.put("aa", "ba"); outerMap.put("ca", innerJson); // 序列化为 JSON 字符串(外层) String outerJson = JSON.toJSONString(outerMap); System.out.println("Outer JSON: " + outerJson); // 解析外层 JSON JSONObject outerObj = JSON.parseObject(outerJson); String nestedJson = outerObj.getString("ca"); // 解析嵌套的内层 JSON JSONObject innerObj = JSON.parseObject(nestedJson); System.out.println("Inner JSON: " + innerObj); } } ``` --- ### 注意事项 - 在处理嵌套 JSON 字符串时,应避免直接拼接字符串,而是通过 `JSON.toJSONString` 来确保结构和转义的正确性。 - 如果 JSON 字符串中包含非法转义字符,fastjson 可能会抛出异常,因此建议在解析前验证输入数据的有效性。 ---
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值