Jackson的使用(json解析)

Jackson:高性能的JSON處理,處理json速度快。
Jackson可以輕鬆的將Java對象轉換成json字符串和xml文檔,同樣也可以將json字符串、xml轉換成Java對象。

代碼如下:

package com.example.administrator.jsckson.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.example.administrator.jsckson.R;
import com.example.administrator.jsckson.entity.Name;
import com.example.administrator.jsckson.entity.Student;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created on 2017/5/4.
 * Author:crs
 * Description:測試jackson
 */
public class TestJacksonActivity extends AppCompatActivity {

    private static final String TAG ="TestJacksonActivity" ;
    private Student student1;
    private ArrayList<Student> list;
    private HashMap<String, Student> map;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_jackson);
        /**
         * 1)JSON屬於序列化與反序列化的內容
         * 2)數據傳輸速度,數據解析速度
         * 3)常用的json解析框架,以及一些配置
         */
        initData();
        ObjectMapper mapper=getDefaultObjectMapper();

        try {
            //1)序列化對象 Object---->String
            String s = mapper.writeValueAsString(student1);
            Log.i(TAG,s);

            //2)序列化集合 list---->String
            String s1 = mapper.writeValueAsString(list);
            Log.i(TAG,s1);

            //3)序列化集合 map---->String
            String s2 = mapper.writeValueAsString(map);
            Log.i(TAG,s2);

            //4)反序列化 json---->Object(這個應該是最常用的)
            Student jsonToObject = mapper.readValue(s, Student.class);
            Log.i(TAG,jsonToObject.toString());

            //5)反序列化 json---->List
            List<Student>  jsonToList = mapper.readValue(s1, new TypeReference<List<Student>>() {});
            Log.i(TAG,jsonToList.toString());

            //6)反序列化 json---->map
            Map<String,Student> jsonToMap = mapper.readValue(s2, new TypeReference<Map<String,Student>>() {});
            Log.i(TAG,jsonToMap.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private static ObjectMapper getDefaultObjectMapper() {
        /**
         * ObjectMapper是JSON操作的核心類,Jackson的所有JSON操作都是在ObjectMapper中實現。
         * ObjectMapper有多個JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介質中。
         * writeValueAsString(Object arg0)把arg0轉成json序列,並把結果輸出成字符串。
         * JSON註解 Jackson提供了一系列註解,方便對JSON序列化和反序列化進行控制.
         */
        ObjectMapper mapper = new ObjectMapper();
        //1)設置將對象轉換成JSON字符串時候(序列化時);序列化與反序列化。//如果對象的屬性爲null或者“”,此屬性不在進行序列化
        mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        //JsonInclude.Include.NON_NULL;屬性爲NULL 不序列化
        //JsonInclude.Include.ALWAYS ;默認
        //2)設置有屬性不能映射時不報錯
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        //3)不能包含ASCII碼
        mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
        //4)設置轉換時的時間格式
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        return mapper;
    }

    private void initData() {
        //準備數據,創建對象
        Name name1 = new Name("陳詩音", "音");
        Name name2 = new Name("陳詩樂", "樂");
        Name name3 = new Name("陳隨心", "心");
        student1 = new Student(1,name1,"語文",new Date());
        Student student2 = new Student(2,name2,"數學",new Date());
        Student student3 = new Student(3,name3,"英語",new Date());
        list = new ArrayList<>();
        list.add(student1);
        list.add(student2);
        list.add(student3);
        map = new HashMap<>();
        map.put("1", student1);
        map.put("2",student2);
        map.put("3",student3);
    }

}
實體模型:

package com.example.administrator.jsckson.entity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.Date;

/**
 * Created on 2017/5/4.
 * Author:crs
 * Description:模型類student
 */
public class Student {
    @JsonIgnore //此註解用於屬性上,作用是進行JSON操作時忽略該屬性。
    private int id;

    @JsonProperty("firstName")//此註解用於屬性上,作用是把該屬性的名稱序列化爲另外一個名稱,如把Name屬性序列化爲firstName
    private Name name;//沒有使用內部類

    private String className;

    @JsonFormat(pattern = "yyyy年MM月dd日") //格式化日期屬性
    private Date birthDay;
    
    public Student(int id, Name name, String className, Date birthDay) {
        this.id = id;
        this.name = name;
        this.className = className;
        this.birthDay = birthDay;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Name getName() {
        return name;
    }

    public void setName(Name name) {
        this.name = name;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public Date getBirthDay() {
        return birthDay;
    }

    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name=" + name +
                ", className='" + className + '\'' +
                ", birthDay=" + birthDay +
                '}';
    }
}

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