1.什么是json
json是一种与开发语言无关的数据传输格式,全程是JavaScript Object Notation;具有易读编写和程序的解析和生产。
2.简单的Json示例
{
"name" : "张三",
"id":"1"
}
3.标准Json数据表示
数据结构:
- Object:
使用花括号{}包含的键值对结构,Key必须是String类型,value可以为任何基本类型或者数据结构 - Array
使用中括号来起始,用逗号来隔开
var employees = [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName": "Carter" }
];
数据演示
{
"name" : "王小二",
"age":"25.2",
"school":"蓝翔",
"major":["挖掘机","炒菜"]
"has_girlfriend" :false
}
3.解析Json
JavaScript原生支持json,可以用eval()函数来解析json,把json文本数据转换成JavaScript对象
var text = "{"name" : "123", age : 1}"
var aa = eval("(" + txt + ")");
alert(aa);
使用JsonObject
导入相关jar包
导入开发包
- commons-io-2.0.1.jar
- commons-lang-2.5.jar
- commons-collections-3.1.jar
- commons-beanutils-1.7.0.jar
- ezmorph-1.0.3.jar
- json-lib-2.1-jdk15.jar
案例:
public class TestBean2Json {
private static void javabean2json() {
City city = new City(1,"广州");
JSONArray jSONArray = JSONArray.fromObject(city);
String jsonJAVA = jSONArray.toString();
System.out.println(jsonJAVA);
//[{"id":1,"name":"广州"}]
}
private static void list2json() {
List<City> cityList = new ArrayList<City>();
cityList.add(new City(1,"广州"));
cityList.add(new City(2,"珠海"));
JSONArray jSONArray = JSONArray.fromObject(cityList);
String jsonJAVA = jSONArray.toString();
System.out.println(jsonJAVA);
//[{"id":1,"name":"广州"},{"id":2,"name":"珠海"}]
}
private static void set2json() {
Set<City> citySet = new LinkedHashSet<City>();
citySet.add(new City(1,"广州"));
citySet.add(new City(2,"珠海"));
JSONArray jSONArray = JSONArray.fromObject(citySet);
String jsonJAVA = jSONArray.toString();
System.out.println(jsonJAVA);
//[{"id":1,"name":"广州"},{"id":2,"name":"珠海"}]
}
private static void javabeanlist2json() {
List<City> cityList = new ArrayList<City>();
cityList.add(new City(1,"中山"));
cityList.add(new City(2,"佛山"));
Province province = new Province(1,"广东",cityList);
JSONArray jSONArray = JSONArray.fromObject(province);
String jsonJAVA = jSONArray.toString();
System.out.println(jsonJAVA);
/*
[
{
"id":1,
"name":"广东"
"cityList":[{"id":1,"name":"中山"},{"id":2,"name":"佛山"}],
}
]
*/
}
private static void map2json() {
List<City> cityList = new ArrayList<City>();
cityList.add(new City(1,"中山"));
cityList.add(new City(2,"佛山"));
Map<String,Object> map = new LinkedHashMap<String,Object>();
map.put("total",cityList.size());//表示集合的长度
map.put("rows",cityList);//rows表示集合
JSONArray jSONArray = JSONArray.fromObject(map);
String jsonJAVA = jSONArray.toString();
System.out.println(jsonJAVA);
//[{"total":2,"rows":[{"id":1,"name":"中山"},{"id":2,"name":"佛山"}]}]
jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1);
System.out.println(jsonJAVA);
}