项目实战-Jackson使用

Jackson使用方法

Java下常见的Json类库有Gson、JSON-lib和Jackson等,Jackson相对来说比较高效,在项目中主要使用Jackson进行JSON和Java对象转换,下面给出一些Jackson的JSON操作方法。

介绍 JSON

准备工作

首先去GitHub下载Jackson工具包,有3个jar包需要下载:
+ jackson-core-2.8.1.jar (核心jar)
+ jackson-annotations-2.8.0.jar (该包提供Json注解支持)
+ jackson-databind-2.8.1.jar (对象序列化支持)

Core modules

Core modules are the foundation on which extensions (modules) build upon. There are 3 such modules currently (as of Jackson 2.6):

Streaming (docs) (“jackson-core”) defines low-level streaming API, and includes JSON-specific implementations
Annotations (docs) (“jackson-annotations”) contains standard Jackson annotations
Databind (docs) (“jackson-databind”) implements data-binding (and object serialization) support on streaming package; it depends both on streaming and annotations packages

Sample

Bean

package com.silion.androidproject.jackson;

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

import java.util.Date;

/**
 * Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解。
 @JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性。
 @JsonFormat 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy年MM月dd日")
 @JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把eMail属性序列化为mail,@JsonProperty("mail")
 */
public class User {
    private String mName;

    @JsonIgnore // 不JSON序列化年龄属性
    private int mAge;

    @JsonFormat(pattern = "yyyy年MM月dd日") // 格式化日期属性
    private Date mBirthday;

    @JsonProperty("mail") // 序列化email属性为mail
    private String mEmail;

    public String getName() {
        return mName;
    }

    public void setName(String name) {
        mName = name;
    }

    public int getAge() {
        return mAge;
    }

    public void setAge(int age) {
        mAge = age;
    }

    public Date getBirthday() {
        return mBirthday;
    }

    public void setBirthday(Date birthday) {
        mBirthday = birthday;
    }

    public String getEmail() {
        return mEmail;
    }

    public void setEmail(String email) {
        mEmail = email;
    }

    @Override
    public String toString() {
        return "User{" +
                "mName='" + mName + '\'' +
                ", mAge=" + mAge +
                ", mBirthday=" + mBirthday +
                ", mEmail='" + mEmail + '\'' +
                '}';
    }
}

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.silion.androidproject.jackson.JacksonActivity">

    <Button
        android:text="Java2Json"
        android:textSize="22sp"
        android:onClick="java2Json"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:text="Json2Java"
        android:textSize="22sp"
        android:onClick="json2Java"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

JacksonActivity

package com.silion.androidproject.jackson;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.silion.androidproject.R;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JacksonActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jackson);
    }

    public void java2Json(View view) {
        SimpleDateFormat dateformat = new SimpleDateFormat("MM/dd/yyyy");

        User user1 = new User();
        user1.setName("silion");
        user1.setEmail("silion@qq.com");
        user1.setAge(2);

        try {
            user1.setBirthday(dateformat.parse("10/01/2014"));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        User user2 = new User();
        user2.setName("silion");
        user2.setEmail("silion@qq.com");
        user2.setAge(2);

        try {
            user2.setBirthday(dateformat.parse("01/01/2015"));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<User> users = new ArrayList<>();
        users.add(user1);
        users.add(user2);

        // User类转JSON
        String json = object2Json(user1);;
        // User类转JSON : {"birthday":"2014年09月30日","name":"silion","mail":"silion@qq.com"}
        System.out.println("User类转JSON : " + json);

        // Map转JSON
        Map<String, User> map = new HashMap<>();
        map.put("silion", user1);
        String jsonmap = object2Json(map);
        // Map转JSON : {"silion":{"birthday":"2014年09月30日","name":"silion","mail":"silion@qq.com"}}
        System.out.println("Map转JSON : " + jsonmap);

        // List转JSON
        String jsonlist = object2Json(users);
        // List转JSON : [{"birthday":"2014年09月30日","name":"silion","mail":"silion@qq.com"},{"birthday":"2014年12月31日","name":"silion","mail":"silion@qq.com"}]
        System.out.println("List转JSON : " + jsonlist);
    }

    /**
     * 将一个object转换为json, 可以使一个java对象,也可以使集合
     *
     * @param object
     * @return
     */
    private String object2Json(Object object) {
        /**
         * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
         * ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。
         * writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。
         * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。
         * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。
         * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。
         */
        ObjectMapper mapper = new ObjectMapper();

        String json = null;
        try {
            json = mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return json;
    }

    public void json2Java(View view) {
        String json = "{\"age\":2,\"birthday\":1412092800000,\"mail\":\"silion@qq.com\",\"name\":\"silion\"}";
        String jsonmap = "{\"silion\":{\"birthday\":\"2014年09月30日\",\"name\":\"silion\",\"mail\":\"silion@qq.com\"}}";
        String jsonlist = "[{\"age\":2,\"birthday\":1412092800000,\"mail\":\"silion@qq.com\",\"name\":\"silion\"},{\"age\":2,\"birthday\":1420041600000,\"mail\":\"silion@qq.com\",\"name\":\"silion\"}]";

        /**
         * ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
         */

        // JSON转Class
        User user = json2Class(json, User.class);
        // JSON转Class : User{name='silion', age=0, birthday=Wed Oct 01 00:00:00 GMT+08:00 2014, email='silion@qq.com'}
        System.out.println("JSON转Class : " + user);

        // JSON转Map
        Map<String, User> map = json2Map(jsonmap);
        // JSON转Map : {silion=User{name='silion', age=0, birthday=Tue Sep 30 08:00:00 GMT+08:00 2014, email='silion@qq.com'}}
        System.out.println("JSON转Map : " + map);

        // JSON转List
        List<User> users = json2List(jsonlist);
        // JSON转List : [User{name='silion', age=0, birthday=Wed Oct 01 00:00:00 GMT+08:00 2014, email='silion@qq.com'}, User{name='silion', age=0, birthday=Thu Jan 01 00:00:00 GMT+08:00 2015, email='silion@qq.com'}]
        System.out.println("JSON转List : " + users);

        // JSON转List2
        List<User> users2 = json2List2(jsonlist);
        // JSON转List2 : [User{name='silion', age=0, birthday=Wed Oct 01 00:00:00 GMT+08:00 2014, email='silion@qq.com'}, User{name='silion', age=0, birthday=Thu Jan 01 00:00:00 GMT+08:00 2015, email='silion@qq.com'}]
        System.out.println("JSON转List2 : " + users2);

    }

    private List<User> json2List2(String jsonlist) {
        ObjectMapper mapper = new ObjectMapper();
        List<User> users = null;
        try {
            users = mapper.readValue(jsonlist, new TypeReference<List<User>>(){
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return users;
    }

    private List<User> json2List(String json) {
        ObjectMapper mapper = new ObjectMapper();
        List<User> users = null;
        try {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, User.class);
            users = mapper.readValue(json, javaType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return users;
    }

    private Map<String, User> json2Map(String json) {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, User> map = null;
        try {
            map = mapper.readValue(json, new TypeReference<Map<String, User>>(){
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    private <T> T json2Class(String json, Class<T> c) {
        ObjectMapper mapper = new ObjectMapper();
        T t = null;
        try {
            t = mapper.readValue(json, c);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值