使用Fastjson序列化与反序列化对象

时间:2023-02-16 08:55:05
1. public class JSONobject {  
2.
3. private String obj;
4. private String color;
5.
6. public String getObj() { return obj; }
7. public void setObj(String obj) { this.obj = obj; }
8. public String getcolor() { return color; }
9. public void setcolor(String color) { this.color = color; }
10.
11.
12. }



1. public class fastjson {  
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. new JSONobject();
6. "red");
7. "s");
8. //序列化
9. String text = JSON.toJSONString(ins);
10. System.out.println(text);
11. //反序列化
12. class);
13. System.out.println(ins1.getColor());
14. System.out.println(ins1.getObj());
15. }
16.
17. }




显示的结果是:

{"color":"red","obj":"s"}
red
s

先建立JSONobject类,对于类里面的每个变量分别都有两个配套函数,一个都不可以少,一个是set,一个是get,其中set,与get后面的字母必须以大写字母开头

如果解析List<object[]>类型的话,需要新版本的fastjson,旧版本的会出错,而且一定要有默认的构造函数


1. public class part {  
2. public String attr;
3. public String value;
4. public String obj;
5.
6. part(String obj,String attr,String value){
7. this.obj = obj;
8. this.attr = attr;
9. this.value = value;
10. }
11. part(){
12.
13. }
14. public String getObj() { return obj; }
15. public void setObj(String obj) { this.obj = obj; }
16. public String getAttr() { return attr; }
17. public void setAttr(String attr) { this.attr = attr; }
18. public String getValue() { return value; }
19. public void setValue(String value) { this.value = value; }
20. }


1. import java.util.ArrayList;  
2. import java.util.List;
3.
4. public class JSONobject {
5.
6. private String obj;
7. private String color;
8. private List<part> parts = new ArrayList<part>();
9.
10. public List<part> getPart() { return parts; }
11. public void setPart(List<part> parts) { this.parts = parts; }
12.
13. public String getObj() { return obj; }
14. public void setObj(String obj) { this.obj = obj; }
15.
16. public String getColor() { return color; }
17. public void setColor(String color) { this.color = color; }
18.
19.
20. }




1. import com.alibaba.fastjson.JSON;  
2.
3. public class fastjson {
4.
5. public static void main(String[] args) {
6. // TODO Auto-generated method stub
7. new JSONobject();
8. "red");
9. "s");
10.
11. new part("head","color","red");
12. new part("foot","color","green");
13.
14. ins.getPart().add(p1);
15. ins.getPart().add(p2);
16. //序列化
17. String text = JSON.toJSONString(ins);
18. System.out.println(text);
19. //反序列化
20. class);
21. System.out.println(ins1.getColor());
22. System.out.println(ins1.getObj());
23. }
24.
25. }


​http://code.alibabatech.com/wiki/display/FastJSON/Tutorial​