以下两种方法我都用过
方法一:
String jstr="{‘json‘:‘jsonvalue‘,‘bool‘:true,‘int‘:1,‘double‘:‘20.5‘}";JSONObject json=JSONObject.fromObject(jstr);boolean bool=json.getBoolean("bool");int i=json.getInt("int");double d=json.getDouble("double");String value=json.getString("json");System.out.println("bool="+String.valueOf(bool)+"\tjson="+value+"\tint="+i+"\tdouble="+d); 假如你是有一个bean对象class User{private String name;private String psw;//封装getter/setter省略}String u="{‘name‘:‘sail331x‘,‘psw‘:‘123456789‘}";User user=(User)JSONObject.toBean(JSONObject.fromObject(u),User.class);就可以了。把一个user变成json对象:JSONObject juser=JSONObject.fromObject(user);String jstr=juser.toString();//这个就变成json字符串了 方法二:
声明一个Person 实体类:
package hb;
import java.util.Date;
public class Person {
String id;
int age;
String name;
Date birthday;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
//测试json数据转换
package hb;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
public class JsonToList {
public static void main(String[] args) {
String json="[{‘name‘:‘huangbiao‘,‘age‘:15},{‘name‘:‘liumei‘,‘age‘:14}]";
JSONArray jsonarray = JSONArray.fromObject(json);
System.out.println(jsonarray);
List list = (List)JSONArray.toCollection(jsonarray, Person.class);
Iterator it = list.iterator();
while(it.hasNext()){
Person p = (Person)it.next();
System.out.println(p.getAge());
}
}
@Test
public void jsonToList1(){
String json="[{‘name‘:‘huangbiao‘,‘age‘:15},{‘name‘:‘liumei‘,‘age‘:14}]";
JSONArray jsonarray = JSONArray.fromObject(json);
System.out.println(jsonarray);
List list = (List)JSONArray.toList(jsonarray, Person.class);
Iterator it = list.iterator();
while(it.hasNext()){
Person p = (Person)it.next();
System.out.println(p.getAge());
}
}
@Test
public void jsonToList2(){
String json="[{‘name‘:‘huangbiao‘,‘age‘:15},{‘name‘:‘liumei‘,‘age‘:14}]";
JSONArray jsonarray = JSONArray.fromObject(json);
System.out.println(jsonarray);
System.out.println("------------");
List list = (List)JSONArray.toList(jsonarray, new Person(), new JsonConfig());
Iterator it = list.iterator();
while(it.hasNext()){
Person p = (Person)it.next();
System.out.println(p.getAge());
}
}
}
将list对象转为JSON字符串数组:
package hb;
import java.util.LinkedList;
import java.util.List;
import net.sf.json.JSONArray;
public class ListToJson {
public static void main(String[] args) {
List list = new LinkedList();
for(int i=0;i<3;i++){
Person p = new Person();
p.setAge(i);
p.setName("name"+i);
list.add(p);
}
JSONArray jsonarray = JSONArray.fromObject(list);
System.out.println(jsonarray);
}
}