json:是一种轻量级的数据交换格式。主要由数组和对象两种形式,通过不同的组合,形式复杂的json串。
1. 第一种json格式:
<script type="text/javascript">
var p={"name":"ljf","age":"23"};
alert(p.name);
alert(p.age);
</script>
2. 第二种json格式:
<script type="text/javascript">
var people =[
{"firstName":"Brett","email": "brett@newInstance.com" },
{"firstName":"Mary","email": "mary@newInstance.com" }
];
for(var k=0;k<people.length;k++){
alert(people[k].firstName);
}
</script>
3. 第三种json格式:
<script type="text/javascript">
var people ={
"programmers":
[
{"firstName":"Brett", "email": "brett@newInstance.com" },
{"firstName":"Jason", "email": "jason@servlets.com" }
]
};
var subName=people.programmers;
for(var k=0;k<subName.length;k++){
alert(subName[k].firstName);
}
</script>
4. 第四种json格式:
<scriptlanguage="JavaScript">
varpeople ={
"programmers": [
{ "firstName":"Brett", "email": "brett@newInstance.com" },
{ "firstName": "Jason", "email":"jason@servlets.com" },
{ "firstName": "Elliotte","lastName":"Harold", "email":"elharo@macfaq.com" }
],
"authors": [
{ "firstName": "Isaac", "genre": "sciencefiction" },
{ "firstName": "Tad", "genre":"fantasy" },
{ "firstName": "Frank", "genre": "christianfiction" }
],
"musicians": [
{ "firstName": "Eric", "instrument": "guitar" },
{ "firstName": "Sergei", "instrument":"piano" }
]};
window.alert(people.programmers[1].firstName);
window.alert(people.musicians[1].instrument);
</script>
5. 第五种json格式:
<script language="JavaScript">
var people ={
"username":"mary",
"age":"20",
"info":{"tel":"1234566","celltelphone":788666},
"address":[
{"city":"beijing","code":"1000022"},
{"city":"shanghai","code":"2210444"}
]
};
window.alert(people.username);
window.alert(people.info.tel);
window.alert(people.address[0].city);
</script>
后台的组合拼接:
public static void main(String[] args) {
JsonUtil su=new JsonUtil();
String str="{'name':ljf}";
String hou=su.string2json(str);
System.out.println(hou);
List<Ha> list=new ArrayList<Ha>();
Ha ha=new Ha();
ha.setAge("11");
ha.setName("ljf");
list.add(ha);
Ha ha2=new Ha();
ha2.setAge("34");
ha2.setName("沙发");
list.add(ha2);
String jian=su.list2json(list);
System.out.println(jian);
}
结果显示:
{'name':ljf}
[{"age":"11","name":"ljf"},{"age":"34","name":"沙发"}]
3.json格式要求高,需要注意一下问题:
1. Stringstr="{'name':'"+name+"','pwd':'"+pwd+"'}";//键值对均采用单引号
{'name':'d','pwd':'d'}
2.Stringstr="{\"name\":\" "+name+"\",\"pwd\":\" "+pwd+ " \"}";//键值对采用双引号
{"name":" 4","pwd":" d3 "}
2. Stringstr="{'name':"+name+",'pwd':"+pwd+"}";//值没有采用引号,在前台获取不到数据;
总结:确保json串的键和值都得有引号;