002.JSON類の使用

3017 ワード

fastjsonシーケンス化と逆シーケンス化の場合、JSONは最も一般的なクラスですが、JSONクラスの使用を見てみましょう

1.シーケンス化

package com.shxt.test01;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shxt.model.Group;

public class     {
    public static void main(String[] args) {
        Group group = new Group();  
        group.setId(1);  
        group.setName("   ");  
          
        // toJSONObject, javabean --> json  
        JSONObject object = (JSONObject)JSON.toJSON(group);  
        System.out.println(object.toJSONString());  
          
        // list --> json  
        List groups = new ArrayList<>();  
        for (int i = 0; i < 3; i++) {  
            Group group2 = new Group();  
            group2.setId(i+1);  
            group2.setName((i+1)+"  ");  
            groups.add(group2);  
        }  
        System.out.println(JSON.toJSON(groups));  
          
        // map --> json  
        Map map = new HashMap();  
        map.put("id", 1);  
        map.put("name", "   ");  
        System.out.println(JSON.toJSON(map));
        
    }
}


2.逆シーケンス化

package com.shxt.test01;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.shxt.model.Group;

public class      {
    public static void main(String[] args) {
        String group = "{\"name\":\"   \",\"id\":1}";
        String groups = "[{\"name\":\"1  \",\"id\":1},{\"name\":\"2  \",\"id\":2},{\"name\":\"3  \",\"id\":3}]";
        // json --> javabean  
        Group g = JSON.parseObject(group, Group.class);  
        System.out.println(g);  
                  
        // list --> json  
        List gs = (List)JSON.parseObject(groups,new TypeReference>(){});  
        for (Group lg : gs) {  
            System.out.println(lg.toString());  
        }
        
        String map = "{\"name\":\"   \",\"id\":1}";
        
        Map m= JSON.parseObject(map, Map.class);
        System.out.println(m); 
        
    }
}
package com.shxt.model;

public class Group {
    private Integer id;
    private String name;
    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;
    }
    @Override
    public String toString() {
        return "Group [id=" + id + ", name=" + name + "]";
    }
    

}