使用Json字符串转化成含多层list集合的对象及多层对象Json字符串

本文详细介绍Java中对象与JSON字符串互相转换的方法,包括三种不同的转换方式:使用JSONObject和JSONArray,以及推荐的Gson库。同时,展示了如何处理包含List集合的对象转换,并介绍了多层对象的JSON转换及反序列化过程。

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

1.对象转json字符串


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Test{
    public static void main(String[] args) {
		Student stu = new Student("xiaoming",21);
                //第一种方式 对象转JSON
		JSONObject jsonObject = JSONObject.fromObject(stu);
		String jsonData1 = jsonObject.toString();
		
                //第二种方式 对象转JSON 该种可以转成List<Object>转成JSON
		JSONArray jsonarray = JSONArray.fromObject(stu);
		String jsonData2 = jsonarray.toString();
		
                //第三种方式 对象转JSON 推荐使用该种方法
		Gson gson = new Gson();
		String jsonData3 = gson.toJson(stu);
		
		System.out.println(jsonData1);
		System.out.println(jsonData2);
		System.out.println(jsonData3);

                //结果信息:
                {"age":21,"name":"xiaoming"}
                [{"age":21,"name":"xiaoming"}]
                {"name":"xiaoming","age":21}
    }
}

2.json字符串转对象

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class JsonResult {

	public int code = 0;
	public String info = "success";
	public Object attach = null;
}

public class Test{
    public static void main(String[] args) {
        //【1】对象转json,该对象套有List集合对象
        Student stu = new Student("xiaoming",21);
	List<Student> list = new ArrayList<Student>();
	list.add(stu);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setAttach(list);
        String jsonData = gson.toJson(jsonResult);
        //jsonData打印结果:{"code":0,"info":"success","attach":[{"name":"xiaoming","age":21}]}

        //【2】多层对象转JSON
        String jsonDatas = "{'code':0,'info':'success','attach':[{'name':'xiaoming','age':21}]}"
        //关键步骤
        JsonResult json = gson.fromJson(jsonDatas, new TypeToken<JsonResult>(){}.getType());
	List<Student> student= (List<Student>)json.getAttach();
	System.out.println(student);

    }
}

3.json字符串转对象

import com.alibaba.fastjson.JSON;

public static void main(String [] args){
        String jsonData = "{'requestTime':'','method':'','exchangeType':'6666','body':[{'id':888888888,'czsj':'20181128074127'}],'exchangeCode':''}";
        JSON.DEFFAULT_DATE_FORMAT = "yyyyMMddHHmmss";
        RequestJsonData<TZjxx> requestJsonData = JSON.parseObject(jsonData,
            new TypeReference<RequestJsonData<TZjxx>>() {
        }.getType());
        List<TZjxx> List = requestJsonData.getBody();
        Timestamp czsj = List.get(0).getCzsj();
        System.out.print(czsj)
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值