Android使用Gson解析JSON数据

package com.gaoo.httpclientdemo;

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

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gaao
 */
public class ParseJsonActivity extends AppCompatActivity {

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

        //  arrayToJson(); //数组转换成 json
        //collectionToJson(); // 将集合 转换成 jsonm
        //  mapToJson(); // Map转化为 json 串

        //studentToJson();    //示例如何将任意的 Java 类转换为 json 串
     //   jsonToStudent();     //示例如何 json 串转化成 Java对象。

        gsonFieldExample();     //示例如何利用Gson处理一个对象的某一字段。
    }

    private void gsonFieldExample() {
        Calendar dob = Calendar.getInstance();
        dob.set(1990, 10, 11);
        People people = new People("John", "350 Banana St.", dob.getTime());
        people.setSecret("This is a secret!");

        Gson gson = new Gson();
        String json = gson.toJson(people);
        System.out.println("json = " + json);
    }

    /**
     * 示例如何 json 串转化成 Java对象
     */
    private void jsonToStudent() {

        String json = "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}";

        Gson gson = new Gson();
        Student student = gson.fromJson(json, Student.class);

        System.out.println("student.getName()        = " + student.getName());
        System.out.println("student.getAddress()     = " + student.getAddress());
        System.out.println("student.getDateOfBirth() = " + student.getDateOfBirth());
        System.out.println("json 串转化成 Java对象 ");

    }

    /**
     * 示例如何将一个 Student 对象转换成 json 串,实际操作中我们也可以将任意的 Java 类转换为 json 串
     */
    private void studentToJson() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2000, 10, 10, 10, 10, 10);
        Student student = new Student("深冬", "Menlo Park", calendar.getTime()); //学生对象

        Gson gson = new Gson();
        String json = gson.toJson(student);
        System.out.println("json = " + json);
    }

    /**
     * 示例如何将java.util.Map转化成 json 串,然后再将 json 串转换为java.util.Map。
     */
    private void mapToJson() {
        Map colours = new HashMap();
        colours.put("BLACK", "#000000");
        colours.put("RED", "#FF0000");
        colours.put("GREEN", "#008000");
        colours.put("BLUE", "#0000FF");
        colours.put("YELLOW", "#FFFF00");
        colours.put("WHITE", "#FFFFFF");

        //将map集合 转换为JSON字符串。
        Gson gson = new Gson();
        String json = gson.toJson(colours);
        System.out.println("json = " + json);

        System.out.println(" ------分割线1 ----------------------------- ");

        //将JSON字符串转换为 map集合
        Type type = new TypeToken>() {
        }.getType();
        Map map = gson.fromJson(json, type);
        for (String key : map.keySet()) {
            System.out.println("map.get = " + map.get(key));
        }
        System.out.println(" ------分割线2 ----------------------------- ");
    }


    //    以下示例如何将Java集合转换为符合 json 规则的字符串。以下示例如何将Java集合转换为符合 json 规则的字符串。
    private void collectionToJson() {
        //将 string数组转换为 json字符串
        List names = new ArrayList();
        names.add("大清盐商");
        names.add("康熙大帝");
        names.add("雍正王朝");
        names.add("乾隆王朝");

        Gson gson = new Gson();
        String jsonNames = gson.toJson(names);
        System.out.println("jsonNames = " + jsonNames);
        System.out.println(" ------分割线1 ----------------------------- ");
        //将 学生类对象 转换为 json字符串

        List students = new ArrayList();
        students.add(new Student("大清盐商", "Apple St", new Date(2000, 10, 1)));
        students.add(new Student("康熙大帝", "Banana St", null));
        students.add(new Student("雍正王朝", "Grape St", new Date(2000, 5, 21)));
        students.add(new Student("乾隆王朝", "Mango St", null));

        gson = new Gson();
        String jsonStudents = gson.toJson(students);
        System.out.println("jsonStudents = " + jsonStudents);
        System.out.println(" ------分割线2 ----------------------------- ");

        //将JSON字符串为一个Student对象。
        Type type = new TypeToken>() {
        }.getType();
        List studentList = gson.fromJson(jsonStudents, type);

        for (Student student : studentList) {
            System.out.println("student.getName() = " + student.getName());
            System.out.println("student.getName() = " + student.getAddress());
            System.out.println("student.getName() = " + student.getDateOfBirth());
        }

    }

//*********************我是分割线*********************************************************

    /**
     * 示例如何将一个数据转换成 json 串并使用 Gson.toJson() 方法将数组序列化为 JSON,
     * 以及Gson.fromJson() 方法将 JSON 串反序列化为 java 数组
     */
    private void arrayToJson() {

        int[] numbers = {1, 2, 3, 4, 5, 6, 7};
        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

        // 1. 创建 gson对象
        Gson gson = new Gson();
        //2.把字符数组转换为 json串
        String numbersJson = gson.toJson(numbers);
        //3.把字符串数组转换为 json串
        String strJson = gson.toJson(days);

        //4.把 json串转换成 数组
        int[] numberArr = gson.fromJson(numbersJson, int[].class);
        for (int i = 0; i < numberArr.length; i++) {
            System.out.println(numberArr[i] + "数字数组");
        }

        // //5.把 json串转换成 字符串数组
        String[] weekDays = gson.fromJson(strJson, String[].class);
        for (int i = 0; i < weekDays.length; i++) {
            System.out.println(weekDays[i] + " 字符串数组 ");
        }
//-------------------------------------------------------------------------------
        //多维数组 转换成 json
        int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
        String json = gson.toJson(data);
        System.out.println("Data = " + json);

        // 转换 json串 为多维数组 将JSON字符串到int的多维数组
        int[][] dataMap = gson.fromJson(json, int[][].class);
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                System.out.print(data[i][j] + " ");
            }
            System.out.println("");
        }
    }


}

下面是用到的 JavaBean对象

package com.gaoo.httpclientdemo;

import java.util.Date;

public class Student {
    private String name;
    private String address;
    private Date dateOfBirth;

    public Student() {
    }

    public Student(String name, String address, Date dateOfBirth) {
        this.name = name;
        this.address = address;
        this.dateOfBirth = dateOfBirth;
    }

    public String getName() {
        return name;
    }

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

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
}

package com.gaoo.httpclientdemo;

import java.util.Date;

/**
 * Created by Administrator on 2016/7/7.
 */
public class People {

    private String name;
    private String address;
    private Date dateOfBirth;
    private Integer age;
    private transient String secret;

    public People(String name, String address, Date dateOfBirth) {
        this.name = name;
        this.address = address;
        this.dateOfBirth = dateOfBirth;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }
}

你可能感兴趣的:(json)