Jackson框架

Jackson框架

一、Jackson簡介

       Jackson可以輕鬆的將Java對象轉換成json對象和xml文檔,同樣也可以將json、xml轉換成Java對象。相比json-lib框架,Jackson所依賴的jar包較少,簡單易用並且性能也要相對高些。

二、Jackson使用

2.1、ObjectMapper的使用

    建立兩個類Address、Employee

public class Address {
    private String street;
    private String city;
    private int zipCode;
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
        this.street = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public int getZipCode() {
        return zipCode;
    }
    public void setZipcode(int zipcode) {
        this.zipCode = zipcode;
    }
    @Override
    public String toString(){
        return getStreet() + ", "+getCity()+", "+getZipCode();
    }
}

public class Employee {
    private int id;
    private String name;
    private int age;
    private BigDecimal salary;
    private String designation;
    private Address address;
    private long[] phoneNumbers;
    private Map<String, String> personalInformation;
    /*Getter and Setter Methods*/
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public BigDecimal getSalary() {
        return salary;
    }

    public void setSalary(BigDecimal salary) {
       this.salary = salary;
    }
    public String getDesignation() {
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
    }
    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
    public long[] getPhoneNumbers() {
        return phoneNumbers;
    }

    public void setPhoneNumbers(long[] phoneNumbers) {
        this.phoneNumbers = phoneNumbers;
    }
    public Map<String, String> getPersonalInformation() {
        return personalInformation;
    }
    public void setPersonalInformation(Map<String, String> personalInformation) {
        this.personalInformation = personalInformation;
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("ID: " + getId() + "\n");
        sb.append("Name: " + getName() + "\n");
        sb.append("Age: " + getAge() + "\n");
        sb.append("Salary: $" + getSalary() + "\n");
        sb.append("Designation: " + getDesignation() + "\n");
        sb.append("Phone Numbers: " + Arrays.toString(getPhoneNumbers()) + "\n");
        sb.append("Address: " + getAddress() + "\n");
        sb.append("Personal Information:" + getPersonalInformation() + "\n");
        return sb.toString();

    }

}

json格式的文件data.json如下:

{
  	 "id" : 123,
 	 "name" : "Henry Smith",
 	 "age" : 28,
  	 "salary" : 2000,
 	 "designation" : "Programmer",
  	 "address" : {
    	"street" : "Park Avn.",
    	"city" : "Westchester",
    	"zipcode" : 10583
 	 },
  	"phoneNumbers" : [ 654321, 222333 ],
  	"personalInformation" : {
    	"gender" : "Male",
    	"maritialstatus" : "Married"
	}
}

1、從文件中讀取json或向文件中寫入json

//Jackson讀取json文件,將json數據轉化爲對象
	public void testJsonToObject() throws JsonParseException, JsonMappingException, IOException{
        ObjectMapper objectMapper = new ObjectMapper();
        Employee emp = objectMapper.readValue(new File("src/data.json"), Employee.class);
        System.out.println(emp.toString());
	}
	//Jackson將java對象轉化爲json字符串並輸出
	public void testObjectTojson() throws JsonParseException, JsonMappingException, IOException{
        ObjectMapper objectMapper = new ObjectMapper();
        Employee emp = objectMapper.readValue(new File("src/data.json"), Employee.class);
        //將對象轉化爲json格式,並存入到文件中
        objectMapper.writeValue(new File("src/data1.json"), emp);
        //將對象轉化爲json格式數據,並輸出到控制檯上
        objectMapper.writeValue(System.out, emp);
        
//        StringWriter  str =new StringWriter();
//        JsonGenerator s=new JsonFactory().createGenerator(str);
//        objectMapper.writeValue(s, emp);
//        String data =new String();
//        str.write(data);
//        System.out.println(data);
	}

2、從InputStream讀入或向OutPutStream寫出

public void testInputStream() throws JsonParseException, JsonMappingException, IOException{
        ObjectMapper objectMapper = new ObjectMapper();
        Employee emp = objectMapper.readValue(new FileInputStream("src/data.json"), Employee.class);
        System.out.println(emp.toString());
	}
	public void testOutPutStream() throws JsonParseException, JsonMappingException, IOException{
        ObjectMapper objectMapper = new ObjectMapper();
        Employee emp = objectMapper.readValue(new File("src/data.json"), Employee.class);
        //將對象轉化爲json格式,並存入到文件中
        objectMapper.writeValue(new FileOutputStream("src/data1.json"), emp);

        //JsonNode node = mapper.readTree(new File("country2.json"));

       //將對象轉化爲json格式數據,並輸出到控制檯上
        objectMapper.writeValue(System.out, emp);

	}

3、從URL中讀取數據(若URL返回的滿足Employee類的json數據)

Employee emp1 = objectMapper.readValue("http://www.xxx.com/xxx", Employee.class);
JsonNode jsonNode = objectMapper.readTree("http://www.xxx.com/xxx");

4、常用的方法

//將user對象轉化爲json格式字符串
String json=mapper.writeValueAsString(user)

//將json格式的字符串轉化爲對象,示例如下:
Map m = mapper.readValue(json, Map.class)
Employee emp = objectMapper.readValue(new File("src/data.json"), Employee.class);


2.2、JsonGenerator

public void testJsonGenerator() throws IOException{
		URL url =new URL("http://www.xxx.com/xxx");
		URLConnection urlConnection = url.openConnection();
		urlConnection.setDoOutput(true);
		urlConnection.setDoInput(true);
		
		//產生一個JsonGenerator類
		JsonFactory jsonFactory = new JsonFactory();
		JsonGenerator jsonGenerator = jsonFactory.createGenerator(urlConnection.getOutputStream(), JsonEncoding.UTF8);
		jsonGenerator.writeString("wwwwwwwww");		
		jsonGenerator.writeStartObject();
		jsonGenerator.writeStringField("brand", "Mercedes");
		jsonGenerator.writeNumberField("doors", 5);
		jsonGenerator.writeEndObject();
		jsonGenerator.close();
	}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章