标签:
1. 把java 对象列表转换为json对象数组,并转为字符串
2.把java对象转换成json对象,并转化为字符串
3.把JSON字符串转换为JAVA 对象数组
4.把JSON字符串转换为JAVA 对象
str = "{\"lendperson\":\"李四\",\"lendcompany\":\"有限公司\",\"checkperson\":\"李四\",
\"lenddate\":\"2010-07-19T00:00:00\",\"lendcounts\":4,\"
passports\":[{\"passportid\":\"d\",\"name\":\"李豫川\",\"passporttype\":\"K\"},
{\"passportid\":\"K9051\",\"name\":\"李平\",\"passporttype\":\"K\"},
{\"passportid\":\"K90517\",\"name\":\"袁寒梅\",\"passporttype\":\"K\"},
{\"passportid\":\"K905199\",\"name\":\"贺明\",\"passporttype\":\"K\"}]}";
------------------------------------------------------自己动手写的代码------------------------------------------------------------
package com.springDemo.animal;
/**
* @ClassName: Cat
* @Description: 测试用的实体类
* @Author:huangshijie
* @CreateDate:2015年1月15日 上午10:53:30
* @Modifior:
* @ModifyDate:
* @ModifyNotes:
*/
public class Cat {
private String name;
private String sex;
private String color;
public Cat(){}
public Cat(String name,String sex,String color){
this.name = name;
this.sex =sex;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
package com.springDemo.animal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONArray;
/**
* @ClassName: EntityFromJSON
* @Description: 从JSON转成实体类的ArrayList
* @Author:huangshijie
* @CreateDate:2015年1月15日 上午10:52:53
* @Modifior:
* @ModifyDate:
* @ModifyNotes:
*/
public class EntityFromJSON {
public static void main(String[] args){
Cat cat1 = new Cat("cat1","male","black");
Cat cat2 = new Cat("cat2","female","white");
Cat cat3 = new Cat("cat3","male","grey");
Cat cat4 = new Cat("cat4","female","black");
ArrayList<Cat> catList = new ArrayList<Cat>();
catList.add(cat1);
catList.add(cat2);
catList.add(cat3);
catList.add(cat4);
JSONArray jsonArray = JSONArray.fromObject(catList);
@SuppressWarnings("unchecked")
List<Cat> catList2 = (List<Cat>)JSONArray.toCollection(jsonArray, Cat.class);
Iterator<Cat> iterator = catList2.iterator();
while(iterator.hasNext()){
Cat tmpCat = iterator.next();
System.out.print(tmpCat.getName()+",");
System.out.print(tmpCat.getSex()+",");
System.out.println(tmpCat.getColor());
}
}
}
标签:
原文地址:http://www.cnblogs.com/huangshijie/p/4225721.html