fastJson中Object转换

import java.util.*;
import com.alibaba.fastjson.*;

public class App {
    
    
    public static void main(String[] args) throws Exception {
    
    
        Collection<Object> li = new ArrayList<>();
        
        li.add("str");
        li.add(-1);
        li.add(false);
        li.add(null);
        li.add(new Point(0.1f, 0.9f, "s", "t", "ring", null));
        Map<String,Object> map = new HashMap<>();
        map.put("",new Point(10.1f, -9.9f, "@", "%", "?", "."));
        li.add(map);
        JSONArray ja = new JSONArray();
        ja.addAll(li);
        
        System.out.println(ja);
        
        Point p = ja.getObject(4, Point.class);
        Set<String> set = p.getData();
        for (String s: set) {
    
    
            System.out.println(s);
        }
        
        p=ja.getJSONObject(5).getObject("", Point.class);
        set = p.getData();
        for (String s: set) {
    
    
            System.out.println(s);
        }
    }
}

class Point {
    
    
    private float x;
    private float y;
    private Set<String> data;

    Point(float x, float y, String... data) {
    
    
        this.x = x;
        this.y = y;
        this.data = new HashSet<>();
        for (String string: data) {
    
     this.data.add(string); }
    }
    public float getX() {
    
     return x; }
    public void setX(float x) {
    
     this.x = x; }
    public float getY() {
    
     return y; }
    public void setY(float y) {
    
     this.y = y; }
    public Set<String> getData() {
    
     return data; }
    public void addData(String v) {
    
     this.data.add(v); }
    public void clearData(String v) {
    
     this.data.remove(v); }

    @Override
    public String toString() {
    
     return "Point [data=" + data + "]"; }
}

结果:

["str",-1,false,null,{"data":[null,"s","t","ring"],"x":0.1,"y":0.9},{"":{"data":["@","%",".","?"],"x":10.1,"y":-9.9}}]
null
s
t
ring
@
%
.
?

猜你喜欢

转载自blog.csdn.net/dscn15848078969/article/details/114482018