一、JSON简介
JSON:JavaScript对象表示法(JavaScript Object Notation)
类似xml :存储和交换信息的语法
比xml更快、更易解析
JSON语法规则:
1、数据在名称/值对中
2、数据有逗号分隔
3、花括号保存对象
4、方括号保存数组
JSON值:
1、数字:整数或浮点数
2、字符串:在双引号中
3、逻辑值:true false
4、数组:在方括号中
5、对象:在花括号中
6、null
二、在JAVA中使用JSONObject生成json
所需要的包
commons-httpclient-3.1.jar
commons-lang-2.4.jar
commons-logging-1.1.1.jar
json-lib-2.4-jdk15.jar
ezmorph-1.0.6.jar
commons-collections-3.2.1.jar
1、bean转为Json
2、List转为Json
3、Map转为Json
HashMap<String, Comparable> map = new HashMap<String, Comparable>();
map.put("name", "hzucmj");
map.put("age", 22);
JSONObject json = JSONObject.fromObject(map);
System.out.println(json.toString()); //结果为:{"name":"hzucmj","age":22}
三、JSON转换的四种各种情况:
1. //把java 对象列表转换为json对象数组,并转为字符串
JSONArray array = JSONArray.fromObject(userlist);
String jsonstr = array.toString();
2.//把java对象转换成json对象,并转化为字符串
JSONObject object = JSONObject.fromObject(invite);
String str=object.toString());
3.//把JSON字符串转换为JAVA 对象数组
String personstr = getRequest().getParameter("persons");
JSONArray json = JSONArray.fromObject(personstr);
List<InvoidPerson> persons = (List<InvoidPerson>)JSONArray.toCollection(json, nvoidPerson.class);
4.//把JSON字符串转换为JAVA 对象
JSONObject jsonobject = JSONObject.fromObject(str);
PassportLendsEntity passportlends = null;
try {
//获取一个json数组
JSONArray array = jsonobject.getJSONArray("passports");
//将json数组 转换成 List<PassPortForLendsEntity>泛型
List<PassPortForLendsEntity> list = new ArrayList<PassPortForLendsEntity>();
for (int i = 0; i < array.size(); i++) {
JSONObject object = (JSONObject)array.get(i);
PassPortForLendsEntity passport = (PassPortForLendsEntity)JSONObject.toBean(object,
PassPortForLendsEntity.class);
if(passport != null){
list.add(passport);
}
}
//转换PassportLendsEntity 实体类
passportlends = (PassportLendsEntity)JSONObject.toBean(jsonobject, PassportLendsEntity.class);
str = "{\"lendperson\":\"李四\",\"lendcompany\":\"有限公司\",\"checkperson\":\"李四\",
passports\":[{\"passportid\":\"d\",\"name\":\"李豫川\",\"passporttype\":\"K\"},
{\"passportid\":\"K9051\",\"name\":\"李平\",\"passporttype\":\"K\"},
{\"passportid\":\"K90517\",\"name\":\"袁寒梅\",\"passporttype\":\"K\"},
{\"passportid\":\"K905199\",\"name\":\"贺明\",\"passporttype\":\"K\"}]}";
本文部分转载至:http://blog.csdn.net/ygzk123/article/details/8273293
http://www.cnblogs.com/xwdreamer/archive/2011/12/16/2296904.html