Java JSON 之 对象 转 JSON 字符串

http://www.verejava.com/?id=16998577938447

下载依赖 jar 包   

json.jar 


package com.json7;

import org.json.JSONObject;

public class Test
{
    public static void main(String[] args)
    {
        /*
         题目: 建立一个 House 类(编号, 房东,房屋描述,房屋价格,是否出租)
              将 House 的一个对象转成 JSON 字符串
         */
        
        //新建一个 House 对象
        House h=new House(1,"刘虎","2室1厅",4000,true);
        
        //将 House 对象转成 JSON 字符串
        JSONObject jsonObj=new JSONObject(h);
        System.out.println(jsonObj.toString());
        
    }
}





package com.json7;

public class House
{
    //编号, 房东,房屋描述,房屋价格,是否出租
    private int id;
    private String owner;
    private String description;
    private double price;
    private boolean isRent;
    public House(int id, String owner, String description, double price,
            boolean isRent)
    {
        super();
        this.id = id;
        this.owner = owner;
        this.description = description;
        this.price = price;
        this.isRent = isRent;
    }
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
    public String getOwner()
    {
        return owner;
    }
    public void setOwner(String owner)
    {
        this.owner = owner;
    }
    public String getDescription()
    {
        return description;
    }
    public void setDescription(String description)
    {
        this.description = description;
    }
    public double getPrice()
    {
        return price;
    }
    public void setPrice(double price)
    {
        this.price = price;
    }
    public boolean isRent()
    {
        return isRent;
    }
    public void setRent(boolean isRent)
    {
        this.isRent = isRent;
    }
    
    
}

http://www.verejava.com/?id=16998577938447

猜你喜欢

转载自www.cnblogs.com/verejava/p/9236964.html
今日推荐