object与map与json之间的相互转换

1、jar

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.70</version>
    <exclusions>
        <exclusion>
            <groupId>*</groupId>
            <artifactId>*</artifactId>
        </exclusion>
    </exclusions>
</dependency>

2、实体类

//按顺序解析JSON.toJSONString
/*
第一种:通过在实体类添加@JSONType(orders={"name","age","gender","height","weight"})
第二种:在属性上添加@JSONField(ordinal = 1)
 */
@JSONType(orders={"userName","passWord"})
public class User {
    private String userName;
    private String passWord;

一、Object与Json之间的相互转换

@Test
    public void test1(){
        //1、Java对象转化为json字符串
        User user = new User("胡胡", "123");
        String userJson = JSON.toJSONString(user);

        System.out.println("Java对象转化为json字符串" + userJson);

        //2、json字符串转化为Java对象
        String jsonString1 = "{\"passWord\":\"123\",\"userName\":\"胡胡\"}";
        String jsonString2 = "{'passWord':'123','userName':'胡胡'}";
        User userObject = JSON.parseObject(jsonString1, User.class);

        System.out.println("json字符串转化为Java对象" + userObject);

    }

二、Map与Json之间的相互转换

    @Test
    public void test2(){
        //1、map对象转为json字符串
        HashMap<String, String> map = new HashMap<>();
        map.put("胡胡","123");
        map.put("胡胡胡","1234");
        String jsonString = JSONObject.toJSONString(map);
        System.out.println("map对象转为json字符串"+jsonString);

        //2、json字符串转为map对象
        String str = "{\"0\":\"zhangsan\",\"1\":\"lisi\",\"2\":\"wangwu\",\"3\":\"maliu\"}";
        Map mapTypes = JSON.parseObject(str);
        Map<Integer,String> mmap = new HashMap<Integer,String>();
        for (Object obj : mapTypes.keySet()){
            mmap.put(Integer.parseInt((String)obj), (String) mapTypes.get(obj));
        }
        System.out.println("json字符串转为map对象"+mmap);
    }

 

posted @ 2021-07-14 17:01  64Byte  阅读(518)  评论(0编辑  收藏  举报