1.所需要的jar包
2.编写实体类
package com.yun.bean;
public class Product {
private Integer id;
private String name;
private int price;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
3.编写测试类
package com.yun.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.ws.Endpoint;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.yun.bean.Product;
import com.yun.service.User.impl.UserServiceImpl;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//对象转化成json字符串
Product p=new Product();
p.setId(1);
p.setName("刘云生1");
p.setPrice(100);
Product p1=new Product();
p1.setId(2);
p1.setName("刘云生2");
p1.setPrice(100);
List list=new ArrayList();
list.add(0, p);
list.add(1, p1);
JSONArray json=JSONArray.fromObject(list);
String s=json.toString();
System.out.println(s);
//json数组转对象
String json2 = "{name=\"刘云生\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
JSONObject jo=JSONObject.fromObject(json2);
Object o=JSONObject.toBean(jo);
String name=(String) jo.get("name");
System.out.println(jo);
System.out.println(name);
}
}
4.测试结果