1:java对象与json串转换:
java对象—json串:
JSONObject JSONStr = JSONObject.fromObject(object)
String str = JSONStr.toString()
json串—java对象:
JSONObject jsonObject = JSONObject.fromObject( jsonString )
Object pojo = JSONObject.toBean(jsonObject,pojoCalss)
2:java数组对象与json串转换:
java数组—json串:
JSONArray arrayStr = JSONArray.fromObject(List<?>)
String str = arrayStr.toString()
json串—java数组:
JSONArray array = JSONArray.fromObject(str)
List<?>list = JSONArray.toList(array, ?.class)
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,则你自己弄吧
//saveJsonFile("E:\\yindd\\slaughter.json")//json文件存放路径(如:E:\a.json)
String data= ReadFile.readFile("F:\\a.json")
System.out.println(data)
JSONObject jsonObj = JSONObject.fromObject(data)
//得到A对象
JSONArray arrayA=jsonObj.getJSONArray("A")
A a = (A) JSONObject.toBean((JSONArray.fromObject(arrayA.toString()).getJSONObject(0)),A.class)
//得到B集合
JSONArray arrayB=jsonObj.getJSONArray("B")
List<B>listB=new ArrayList<B>()
for(int i=0i<arrayB.size()i++){
B b=(B)JSONObject.toBean((JSONArray.fromObject(arrayB.toString()).getJSONObject(i)),B.class)
listB.add(b)
}
//得到C集合
JSONArray arrayC=jsonObj.getJSONArray("C")
List<C>listC=new ArrayList<C>()
for(int i=0i<arrayB.size()i++){
C c=(C)JSONObject.toBean((JSONArray.fromObject(arrayC.toString()).getJSONObject(i)),C.class)
listB.add(c)
}