利用fastjson将map数据封装到对象中

闲来无事,偶然想到fastjson封装对象的事情,于是便做了一个测试,看来以后可以少些几个工具类了

实体:

package com.site.utils;

import java.util.List;

/**
 * Create by szw on 2017/11/24 10:17
 */
public class Life {
    private String name;//姓名
    private int age;//年龄
    private String country;//国家
    private List<String> friend;

    public Life() {

    }

    @Override
    public String toString() {
        return "Life{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", country='" + country + '\'' +
                ", friend=" + friend +
                '}';
    }

    public String getName() {
        return name;
    }

    public Life(String name, int age, String country, List<String> friend) {
        this.name = name;
        this.age = age;
        this.country = country;
        this.friend = friend;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public List<String> getFriend() {
        return friend;
    }

    public void setFriend(List<String> friend) {
        this.friend = friend;
    }
}

测试:

package com.site.utils;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Create by szw on 2017/11/24 11:16
 */
public class ParseBean {
    public static void main(String[] args) {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", "诸葛亮");
        hashMap.put("age", 27);
        hashMap.put("country", "蜀");
        hashMap.put("friend", new ArrayList<>());
        String s = JSON.toJSONString(hashMap);
        System.out.println(s);
        Life life = JSON.parseObject(s, Life.class);
        System.out.println(life.toString());
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文子阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值