Java对象与JSON字符串互转

本文提供了一个简单的Gson库示例,演示如何将Java对象转换为JSON字符串,以及如何从JSON字符串还原回Java对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java对象与JSON字符串互转


包下载 地址  : http://download.youkuaiyun.com/detail/chenyi0834/4499629


废话不多说,直接上代码。


import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
 
/**
 * Gson的一个简单示例
 *
 * @author Gythialy
 */
public class TestHashMap {
    public static void main(String[] args) {
        // 组织示例数据
        HashMap<String, List<String>> exportInfo = new HashMap<String, List<String>>();
 
        for (int i = 0; i < 10; i++) {
            String className = "classname" + i;
            List<String> properties = new ArrayList<String>();
            for (int j = 0; j < 5; j++) {
                properties.add(className + "-property" + j);
            }
 
            exportInfo.put(className, properties);
        }
 
        // 转换成JSON字符串
        Gson gson = new Gson();
        String json = gson.toJson(exportInfo);
        System.out.println(json);
 
        // 把JSON字符串转换成原来的Java对象
        Type type = new TypeToken<HashMap<String, List<String>>>() {
        }.getType();
 
        HashMap<String, List<String>> fromJson = gson.fromJson(json, type);
 
        for (String key : fromJson.keySet()) {
            List<String> list = fromJson.get(key);
            list.toString();
            System.out.println(String.format("%s:%s", key, list));
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值