java中Json的使用

使用json-lib的程序jar包下载地址:
http://json-lib.sourceforge.net/

JsonTest.java代码如下:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonTest {
    
    @SuppressWarnings("unchecked")
    public static void main(String args[]){
        
        //list集合转换为json代码
        List list = new ArrayList();
        list.add("girl");
        list.add("boy");
        
        JSONArray ja = JSONArray.fromObject(list);
        System.out.println(ja);    
        
        // Map集合转换成json代码
        Map map = new HashMap();
        map.put("name", "kava");
        map.put("bool", Boolean.TRUE);
        map.put("int", new Integer(1));
        map.put("array", new String[]{"a","b"});
        map.put("func", "function(){return 3;}");
        
        JSONObject jo = JSONObject.fromObject(map);
        System.out.println(jo);
        
        //Bean转换成json代码
        JSONObject jsonBean = JSONObject.fromObject(new UserBean("kava","shanghai","88765687"));
        System.out.println(jsonBean);
        
        //一般数据转换为json代码
        JSONArray ja2 = JSONArray.fromObject("['json','shiryu','kava']");
        System.out.println(ja2);
        
        //一组beans转换为json代码
        List list2 = new ArrayList();
        UserBean u1 = new UserBean("shiryu","shanghai","6666");
        UserBean u2 = new UserBean("tina","guangzhou","5587");
        
        list2.add(u1);
        list2.add(u2);
        JSONArray ja3 = JSONArray.fromObject(list2);
        System.out.println(ja3);    
    }    
}

UserBean.java代码如下:

public class UserBean {
    private String username;
    private String city;
    private String tel;
    
    public UserBean() { 
    }
    
    public UserBean(String username,String city,String tel) {
        this.username=username;
        this.city = city;
        this.tel = tel;
    }
    
    public String getUsername() {
        return username;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }
}

也可将json数据转为java数据

import net.sf.json.JSONObject;

public class StringToJson {
    public static void main(String args[]){
    String json = "{name=\"kava\",bool:true,int:1,double:2.2,func:function(a){return a;},array:[1,2]}";
    JSONObject jsonObject = JSONObject.fromObject(json); 
    Object bean = JSONObject.toBean(jsonObject);
    String name = jsonObject.getString("name");
    
    System.out.print(name+"--"+bean.toString());     
    }
}

 

posted on 2017-12-14 12:00  FrankLiner  阅读(4608)  评论(0编辑  收藏  举报

导航