使用JSON.parseObject 对象与MAP之间的转换

使用JSON.parseObject 对象与MAP之间的转换

package com.example.core.mydemo.json5;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;

public class Item {
    private String id;
//    @JSONField(serialize = false)  //fastjson 忽略字段打印
    private String rate;

    private String status;

    public Item() {
    }

    public Item(String id, String rate) {
        this.id = id;
        this.rate = rate;
    }

    @Override
    public String toString() {
        return "Item{" +
                "id='" + id + '\'' +
                ", rate='" + rate + '\'' +
                ", status='" + status + '\'' +
                '}';
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    /**
     * output  {"id":"111"}
     * @param args
     */
    public static void main(String[] args) {
        Item item = new Item();
        item.setId("111");
        item.setRate("56666");
        System.out.println(JSON.toJSONString(item));
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getRate() {
        return rate;
    }

    public void setRate(String rate) {
        this.rate = rate;
    }
}
package com.example.core.mydemo.json5;

import com.alibaba.fastjson.JSON;

import java.util.Map;

/**
 * 使用JSON.parseObject 对象与MAP之间的转换
 * output:
 * map={rate=aaa, id=1, status=00}
 * item2=Item{id='1', rate='aaa', status='00'}
 */
public class Object2MapTest {
    public static void main(String[] args) {
        Item item = new Item();
        item.setRate("aaa");
        item.setId("1");
        item.setStatus("00");

        /**
         * 对象转map
         */
        String json = JSON.toJSONString(item);
        Map map = JSON.parseObject(json, Map.class);
        System.out.println("map=" + map);

        /**
         * map转对象
         */
        String json2 = JSON.toJSONString(map);
        Item item2 = JSON.parseObject(json2, Item.class);
        System.out.println("item2=" + item2.toString());
    }
}

 

posted on 2024-08-09 07:22  oktokeep  阅读(147)  评论(0编辑  收藏  举报