1、先定义一个类对象
package com.basics; import com.alibaba.fastjson.JSONObject; import java.util.List; import java.util.Map; /** * @author admin */ public class students { private Integer id; private String uname; private String hobby; private String dream; private List<Map<String,String>> info; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } public String getDream() { return dream; } public void setDream(String dream) { this.dream = dream; } public List<Map<String, String>> getInfo() { return info; } public void setInfo(List<Map<String, String>> info) { this.info = info; } @Override public String toString(){ return "{"id":""+ id+ "","uname":""+uname+"","hobby":""+hobby+"","dream":""+dream+"","info":"+ JSONObject.toJSONString(info) +"}"; } }
2、实例对象添加数据和转json
package com.basics; import net.sf.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class objectMap { public static void main(String[] args){ students std = new students(); std.setId(123456); std.setUname("ouba"); std.setHobby("rap"); std.setDream("miss"); List<Map<String,String>> info = new ArrayList<Map<String,String>>(); Map<String,String> m = new HashMap<String,String>(); m.put("名字1","欧巴");m.put("name2","哥哥"); info.add(m); std.setInfo(info); System.out.println(std.toString()); //对象转json // JSONObject json = JSONObject.parseObject(std.toString()); // //List<String> line = (List<String>) json.get("info"); // JSONArray line = (JSONArray) json.get("info"); // System.out.println(line.get(1)); JSONObject js = JSONObject.fromObject(std); String st = js.toString(); System.out.println(st); } }
注意,使用JSONObject 需要导入json-lib包,下载地址:链接: https://pan.baidu.com/s/1_TJqAvrth8yO2p-a-N33JA 提取码: q182 复制这段内容后打开百度网盘手机App,操作更方便哦