前言:之前我们学习了如何利用Ajax读取XML,操作繁杂,传输的数据也比较复杂。而使用Json就更方便数据量也较少一点,而且用Ajax传输JSON的时候是纯文本传输,也就是说可以用responseText接收。所以现在的开发之中很少用XML去进行数据交互,一般都是用JSON。
要利用Java生成JSON,需要导入JSON的开发包json-lib-2.4-jdk15.jar所需全部JAR包.rar,然后就可以使用其中的两个核心类:JSONObject和JSONArray。
使用java和第三方开发包生成JSON
package test;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* 我用了两种方法生成JSON对象
*/
public class JsonCreate {
public static void main(String[] args) {
JSONObject jsonObject=new JSONObject();
jsonObject.put("name","浙江");
jsonObject.put("cityCount",2);
//第一种方法,利用jsonArray
JSONArray jsonArray=new JSONArray();
JSONObject c1=new JSONObject();
c1.put("name","宁波");
c1.put("id",1);
JSONObject c2=new JSONObject();
c2.put("name","杭州");
c2.put("id",2);
jsonArray.add(c1);
jsonArray.add(c2);
jsonObject.put("cities",jsonArray);
System.out.println(jsonObject);
//第二种方法,利用List与JavaBean对象
List<City> cityList=new ArrayList<>();
City city1=new City("丽水","晴",3);
City city2=new City("绍兴","雨",4);
cityList.add(city1);
cityList.add(city2);
jsonObject.put("cities",cityList);
System.out.println(jsonObject);
}
}
package test;
public class City {
private String name;
private String weather;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public City(String name, String weather, int id) {
this.name = name;
this.weather=weather;
this.id = id;
}
}
运行结果:
{"name":"浙江","cityCount":2,"cities":[{"name":"宁波","id":1},{"name":"杭州","id":2}]}
{"name":"浙江","cityCount":2,"cities":[{"id":3,"name":"丽水","weather":"晴"},{"id":4,"name":"绍兴","weather":"雨"}]}
使用Java和第三方开发包读取JSON
package test;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonRead {
public static void main(String[] args) {
//注意字符串要进行转义
String str="{\"name\":\"浙江\",\"cityCount\":2,\"cities\":[{\"name\":\"宁波\",\"id\":1},{\"name\":\"杭州\",\"id\":2}]}";
JSONObject jsonObject=JSONObject.fromObject(str);
System.out.println(jsonObject);
System.out.println("省份名称:"+jsonObject.get("name"));
System.out.println("城市数量:"+jsonObject.get("cityCount"));
JSONArray array=jsonObject.getJSONArray("cities");
System.out.println("城市信息:");
for (int i=0;i<array.size();i++){
JSONObject city=array.getJSONObject(i);
System.out.print("\t城市名称:"+city.get("name"));
System.out.println(" 城市编号:"+city.get("id"));
}
}
}
运行结果:
{"name":"浙江","cityCount":2,"cities":[{"name":"宁波","id":1},{"name":"杭州","id":2}]}
省份名称:浙江
城市数量:2
城市信息:
城市名称:宁波 城市编号:1
城市名称:杭州 城市编号:2
你也可以把json数据存到一个txt文本中,读取文件转换为字符串再进行JSON的读取。