1、导入相关的jar包
2、自己从客服端得到相关的流文件,然后处理下。
3、通过对JSON的解析取得相关的数据,代码如下:
package com.mqp.test;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.mqp.entity.Student;
import com.mqp.service.GetEntity;
public class TestJson {
public static void main(String[] args) {
//用json取得单个的对象
Student stu =GetEntity.getStudent();
JSONObject json1 = new JSONObject();
json1.put("student", stu);
System.out.println(json1.toString());
System.out.println("名字:"+json1.getJSONObject("student").getString("name")
+",年龄:"+json1.getJSONObject("student").getInt("age")
+",性别:"+json1.getJSONObject("student").getString("sex"));
System.out.println("------------------------------");
//用json取得对象集合
List<Student> list =GetEntity.getStudents();
JSONObject json2 = new JSONObject();
json2.put("students", list);
//把json放在json数组里边去,在下边好就行循环
JSONArray js = json2.getJSONArray("students");
for (int i = 0; i < js.size(); i++) {
//数组里边单个的对象都是json格式的,所以需要得到JSONObject
JSONObject jso = js.getJSONObject(i);
System.out.print(jso.getString("name")+",");
System.out.print(jso.getInt("age")+",");
System.out.println(jso.getString("sex"));
}
}
}