Java bean 转 Map 时需要使用Fastjson

//方法 一
Map<String, Object> a = (Map<String, Object>)JSON.toJSON(javabean)

//方法 二
Map<String, Object> a = JSON.parseObject(JSON.toJSONString(javabean))

另外也可以使用 使用 BeanUtils

Map beanMap = BeanUtils.describe(javabean);

 

实际例子如下:

package com.qa.Parameters;

public class postParameters {
    private String userName;
    private String password;

    public postParameters(){

    }
    //login
    public postParameters(String userName , String password){
        this.userName = userName;
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName){
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password){
        this.password = password;
    }
}

运行的代码如下:

package com.qa.tests;

import com.alibaba.fastjson.JSON;
import com.qa.Parameters.postParameters;
import java.util.Map;

public class practise {

    public static void main(String[] args){
        postParameters loginParameters = new postParameters("jack","123456");
        //将登录请求对象序列化成json对象
        String userJsonString = JSON.toJSONString(loginParameters);
        Map<String, Object> javabean_map = JSON.parseObject(userJsonString);
        Map<String, Object> javabean_map2 = JSON.parseObject(JSON.toJSONString(loginParameters));
        Map<String, Object> javabean_map3 = (Map<String, Object>)JSON.toJSON(loginParameters);

        System.out.println("userJsonString Type "+ userJsonString.getClass().getName());
        System.out.println("userJsonString  "+ userJsonString);
        System.out.println("javabean_map Type "+ javabean_map.getClass().getName());
        System.out.println("javabean_map  "+ javabean_map);
        System.out.println("javabean_map2 Type "+ javabean_map2.getClass().getName());
        System.out.println("javabean_map2  "+ javabean_map2);
        System.out.println("javabean_map3 Type "+ javabean_map3.getClass().getName());
        System.out.println("javabean_map3  "+ javabean_map3);

    }  

}

输出的结果如下:

userJsonString Type java.lang.String
userJsonString  {"password":"123456","userName":"jack"}
javabean_map Type com.alibaba.fastjson.JSONObject
javabean_map  {"password":"123456","userName":"jack"}
javabean_map2 Type com.alibaba.fastjson.JSONObject
javabean_map2  {"password":"123456","userName":"jack"}
javabean_map3 Type com.alibaba.fastjson.JSONObject
javabean_map3  {"password":"123456","userName":"jack"}