Java样例程序如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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=0i<employees.size()i++) {
JSONObject 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
String fullFileName = "E:/a.json"
File file = new File(fullFileName)
Scanner scanner = null
StringBuilder buffer = new StringBuilder()
try {
scanner = new Scanner(file, "utf-8")
while (scanner.hasNextLine()) {
buffer.append(scanner.nextLine())
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} finally {
if (scanner != null) {
scanner.close()
}
}
System.out.println(buffer.toString())
这是读取文件的方法,至于解析json,则你自己弄吧