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 +
                '}';
    }
}

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