json字符串的生成与解析
json报文如下
{
"data": {
"msg": "成功",
"createTime": 1590119797,
"from": "Atidate",
"to": "CSDN",
"content": {
"deptName": "总部",
"emp": [{
"empId": "100001",
"empSex": "男",
"empName": "张三"
}, {
"empId": "100002",
"empSex": "女",
"empName": "李四"
}],
"deptAdrrs": "北京",
"deptNo": "01"
}
}
}
需要的包
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
json生成
public static void main(String[] args) {
/**
* 生成json数据
*
* */
//当前时间戳(秒)
long time = System.currentTimeMillis() / 1000;
JSONObject json = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("from", "Atidate");
dataJson.put("to", "CSDN");
dataJson.put("createTime", time);
dataJson.put("msg", "成功");
JSONObject dept = new JSONObject();
dept.put("deptNo", "01");
dept.put("deptName", "总部");
dept.put("deptAdrrs", "北京");
JSONObject emp1 = new JSONObject();
emp1.put("empId", "100001");
emp1.put("empName", "张三");
emp1.put("empSex", "男");
JSONObject emp2 = new JSONObject();
emp2.put("empId", "100002");
emp2.put("empName", "李四");
emp2.put("empSex", "女");
JSONArray emp = new JSONArray();
emp.add(emp1);
emp.add(emp2);
dept.put("emp", emp);
dataJson.put("content", dept);
json.put("data", dataJson);
System.out.println(json);
}
json解析
/**
* 解析json数据
* @param json json字符串
*
* */
private static void readJSON(String json){
JSONObject jsonObject = JSONObject.fromObject(json);
JSONObject jsonData = jsonObject.getJSONObject("data");
String to = jsonData.getString("to");
String msg = jsonData.getString("msg");
String from = jsonData.getString("from");
String createTime = jsonData.getString("createTime");
String deptNo = jsonData.getJSONObject("content").getString("deptNo");
String deptName = jsonData.getJSONObject("content").getString("deptName");
String deptAdrrs = jsonData.getJSONObject("content").getString("deptAdrrs");
String empId = (String) jsonData.getJSONObject("content").getJSONArray("emp").getJSONObject(0).get("empId");
String empSex = (String) jsonData.getJSONObject("content").getJSONArray("emp").getJSONObject(0).get("empSex");
String empName = (String) jsonData.getJSONObject("content").getJSONArray("emp").getJSONObject(0).get("empName");
System.out.println("msg:" + msg);
System.out.println("createTime:" + createTime);
System.out.println("from:" + from);
System.out.println("to:" + to);
System.out.println("deptNo:" + deptNo);
System.out.println("deptName:" + deptName);
System.out.println("deptAdrrs:" + deptAdrrs);
System.out.println("empId:" + empId);
System.out.println("empSex:" + empSex);
System.out.println("empName:" + empName);
}