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

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转成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 list = new ArrayList();
	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(){}.getType());
	List student= (List)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 requestJsonData = JSON.parseObject(jsonData,
            new TypeReference>() {
        }.getType());
        List List = requestJsonData.getBody();
        Timestamp czsj = List.get(0).getCzsj();
        System.out.print(czsj)
    }

 

你可能感兴趣的:(使用Json字符串转化成含多层list集合的对象及多层对象Json字符串)