如果不是Android开发环境的话,首先需要引入处理JSON数据的包:json-lib-2.2.3-jdk15.jar
Java样例程序如下:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class DoJSON {
public static void main(String[] args) {
JSONArray employees = new JSONArray(); //JSON数组
JSONObject employee = new JSONObject(); //JSON对象
employee.put("firstName", "Bill"); //按“键-值”对形式存储数据到JSON对象中
employee.put("lastName", "Gates");
employees.add(employee); //将JSON对象加入到JSON数组中
employee.put("firstName", "George");
employee.put("lastName", "Bush");
employees.add(employee);
employee.put("firstName", "Thomas");
employee.put("lastName", "Carter");
employees.add(employee);
System.out.println(employees.toString());
for(int i=0; iJSONObject emp = employees.getJSONObject(i);
System.out.println(emp.toString());
System.out.println("FirstName :\t" + emp.get("firstName"));
System.out.println("LastName : \t" + emp.get("lastName"));
}
}
}
运行效果:
[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]
{"firstName":"Bill","lastName":"Gates"}
FirstName : Bill
LastName : Gates
{"firstName":"George","lastName":"Bush"}
FirstName : George
LastName : Bush
{"firstName":"Thomas","lastName":"Carter"}
FirstName : Thomas
LastName : Carter
使用json解析的jar包:
commons-lang.jar
commons-beanutils.jar
commons-collections.jar
commons-logging.jar
ezmorph.jar
json-lib-2.2.2-jdk15.jar
JSONObject obj =JSONObject.fromString("这里传入json字符串");
就可以使用obj来获取里面的数据了