Gson使用(转的)

下面的例子中我们示例如何将一个数据转换成 json 串,并使用 Gson.toJson() 方法将数组序列化为 JSON,以及Gson.fromJson() 方法将 JSON 串反序列化为 java 数组。

import com.google.gson.Gson;

public class ArrayToJson {
    public static void main(String[] args) {
        int[] numbers = {1, 1, 2, 3, 5, 8, 13};
        String[] days = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

        //
        // Create a new instance of Gson
        //
        Gson gson = new Gson();

        //
        // Convert numbers array into JSON string.
        //
        String numbersJson = gson.toJson(numbers);

        //
        // Convert strings array into JSON string
        //
        String daysJson = gson.toJson(days);
        System.out.println("numbersJson = " + numbersJson);
        System.out.println("daysJson = " + daysJson);

        //
        // Convert from JSON string to a primitive array of int.
        //
        int[] fibonacci = gson.fromJson(numbersJson, int[].class);
        for (int i = 0; i < fibonacci.length; i++) {
            System.out.print(fibonacci[i] + " ");
        }
        System.out.println("");

        //
        // Convert from JSON string to a string array.
        //
        String[] weekDays = gson.fromJson(daysJson, String[].class);
        for (int i = 0; i < weekDays.length; i++) {
            System.out.print(weekDays[i] + " ");
        }
        System.out.println("");

        //
        // Converting multidimensional array into JSON
        //
        int[][] data = {{1, 2, 3}, {3, 4, 5}, {4, 5, 6}};
        String json = gson.toJson(data);
        System.out.println("Data = " + json);

        //
        // Convert JSON string into multidimensional array of 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("");
        }
    }
}

以下是输出结果:

numbersJson = [1,1,2,3,5,8,13]
daysJson = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]
1 1 2 3 5 8 13
Sun Mon Tue Wed Thu Fri Sat
Data = [[1,2,3],[3,4,5],[4,5,6]]
1 2 3
3 4 5

如何将集合转化为 json 串?

下面的例子中我们示例如何将Java集合转换为符合 json 规则的字符串。

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

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

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CollectionToJson {
    public static void main(String[] args) {
        //
        // Converts a collection of string object into JSON string.
        //
        List<String> names = new ArrayList<String>();
        names.add("Alice");
        names.add("Bob");
        names.add("Carol");
        names.add("Mallory");

        Gson gson = new Gson();
        String jsonNames = gson.toJson(names);
        System.out.println("jsonNames = " + jsonNames);

        //
        // Converts a collection Student object into JSON string
        //
        Student a = new Student("Alice", "Apple St", new Date(2000, 10, 1));
        Student b = new Student("Bob", "Banana St", null);
        Student c = new Student("Carol", "Grape St", new Date(2000, 5, 21));
        Student d = new Student("Mallory", "Mango St", null);

        List<Student> students = new ArrayList<Student>();
        students.add(a);
        students.add(b);
        students.add(c);
        students.add(d);

        gson = new Gson();
        String jsonStudents = gson.toJson(students);
        System.out.println("jsonStudents = " + jsonStudents);

        //
        // Converts JSON string into a collection of Student object.
        //
        Type type = new TypeToken<List<Student>>(){}.getType();
        List<Student> studentList = gson.fromJson(jsonStudents, type);

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

以下是输出结果:

jsonNames = ["Alice","Bob","Carol","Mallory"]
jsonStudents = [{"name":"Alice","address":"Apple St","dateOfBirth":"Nov 1, 3900 12:00:00 AM"},{"name":"Bob","address":"Banana St"},{"name":"Carol","address":"Grape St","dateOfBirth":"Jun 21, 3900 12:00:00 AM"},{"name":"Mallory","address":"Mango St"}]
student.getName() = Alice
student.getName() = Bob
student.getName() = Carol
student.getName() = Mallory

如何将Map转化为 json 串?

下面的例子中我们示例如何将java.util.Map转化成 json 串,然后再将 json 串转换为java.util.Map

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

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class MapToJson {
    public static void main(String[] args) {
        Map<String, String> colours = new HashMap<String, String>();
        colours.put("BLACK", "#000000");
        colours.put("RED", "#FF0000");
        colours.put("GREEN", "#008000");
        colours.put("BLUE", "#0000FF");
        colours.put("YELLOW", "#FFFF00");
        colours.put("WHITE", "#FFFFFF");

        //
        // Convert a Map into JSON string.
        //
        Gson gson = new Gson();
        String json = gson.toJson(colours);
        System.out.println("json = " + json);

        //
        // Convert JSON string back to Map.
        //
        Type type = new TypeToken<Map<String, String>>(){}.getType();
        Map<String, String> map = gson.fromJson(json, type);
        for (String key : map.keySet()) {
            System.out.println("map.get = " + map.get(key));
        }
    }
}

以下是输出结果:

json = {"WHITE":"#FFFFFF","BLUE":"#0000FF","YELLOW":"#FFFF00","GREEN":"#008000","BLACK":"#000000","RED":"#FF0000"}
map.get = #FFFFFF
map.get = #0000FF
map.get = #FFFF00
map.get = #008000
map.get = #000000
map.get = #FF0000

如何将对象转换为 json 串?

下面的例子中我们示例如何将一个 Student 对象转换成 json 串,实际操作中我们也可以将任意的 Java 类转换为 json 串,并且实施起来也非常简单,你仅仅需要创建一个 Gson 实例,然后传递将被转化为 json 串的对象,并调用该实例的 toJson 方法即可。

import com.google.gson.Gson;

import java.util.Calendar;

public class StudentToJson {
    public static void main(String[] args) {
        Calendar dob = Calendar.getInstance();
        dob.set(2000, 1, 1, 0, 0, 0);
        Student student = new Student("Duke", "Menlo Park", dob.getTime());

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

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

以下是输出结果:

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

如何将 json 串转换为对象?

下面的例子中我们示例如何 json 串转化成 Java对象。

import com.google.gson.Gson;

public class JsonToStudent {
    public static void main(String[] args) {
        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());
    }
}

以下是输出结果:

student.getName()        = Duke
student.getAddress()     = Menlo Park
student.getDateOfBirth() = Tue Feb 01 00:00:00 CST 2000

如何处理对象的字段?

下面的例子中我们示例如何利用Gson处理一个对象的某一字段。

import com.google.gson.Gson;

import java.util.Calendar;

public class GsonFieldExample {
    public static void main(String[] args) {
        Calendar dob = Calendar.getInstance();
        dob.set(1980, 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);
    }
}

import java.util.Date;

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 = {"name":"John","address":"350 Banana St.","dateOfBirth":"Nov 11, 1980 8:47:04 AM"}
时间: 2024-09-28 01:43:03

Gson使用(转的)的相关文章

用gson和httpclient调用微信公众平台API

吐槽:微信api很无语,部分用xml,部分用json. 最近在找如何调用微信公众平台关于json相关的api比较方便,最后发现httpcliect和gson不错.如果你有更好的方式,请告诉我. 以下代码先了解如何使用gson和httpclient,有功夫再整到我的sophia里 import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.

android之GSON解析JSON

Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库. 比如: <pre name="code" class="java">public class Order { public String id; public String OrderName; @Override public String toString() { return "id:"+id+",OrderNa

利用SharePrefrence和Gson实现实体类的保存与获取

实现需要Gson获者其他能将实体类转换成json的jar包 接下来是主要方法: 保存实体类 public static  void putClass(ModelBase model){//需要实体类继承一个基类           String key=model.getClass().getName();           String value=new Gson().toJson(model);           putString(key, value);       }   获取实

javaWeb笔记:gson

谷歌的Gson.jar: //list转换为json Gson gson = new Gson(); List<Person> persons = new ArrayList<Person>(); String str = gson.toJson(persons); //json转换为list Gson gson = new Gson(); List<Person> persons = gson.fromJson(str, new TypeToken<List&l

Json2:使用gson解析为List和Map

import java.lang.reflect.Type; import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class Json解析成List { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("["

【Android】使用Gson和Post请求和服务器通信

一.需求文档如下: 二.Java代码如下 public class MainActivity extends AppCompatActivity { 26 private final int POST_VALUE = 1; 42 String text = ""; //这里不能获取ID,因为下面还没连接到activity_main,xml TextView textView; //--------------------------------------------定义一个Handl

Android Gson使用笔记

最近在做一个java web service项目,需要用到jason,本人对java不是特别精通,于是开始搜索一些java平台的json类库. 发现了google的gson,因为之前对于protocolbuf有一些了解,带着一些好奇心,我开始使用了gson. 经过比较,gson和其他现有java json类库最大的不同时gson需要序列化得实体类不需要使用annotation来标识需要序列化得字段,同时gson又可以通过使用annotation来灵活配置需要序列化的字段. 下面是一个简单的例子:

如何使用Gson(添加到项目里去)

转载自http://www.th7.cn/Program/Android/201603/783377.shtml 方法一: 1.在Android Studio中按F4快捷键进入Project Structure 2点击+号 . 3.选择Library dependency 4.搜索GSON 5.添加进去 方法二: 在buil的.gradle中输入 compile 'com.google.code.gson:gson:2.6.2' ---------------------------------

JSON格式之GSON解析

JSON格式之GSON解析 最近在做websocket相关,项目需要JSON解析.相较之下感觉google的GSON解析不错. JAVA后台 Gson提供了fromJson()方法来实现从Json相关对象到java实体的方法 1.对象类型 采用上图的第一种方法. Gson gson =new Gson(); User user= gson.fromJson(str, User.class); 2.Map.List等 采用上图的第二种方法. Type type = new TypeToken<Ma

Android JSON 解析库的使用 - Gson 和 fast-json

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C.C++.C#.Java.JavaScript.Perl.Python等).这些特性使JSON成为理想的数据交换语言. 易于人阅读和编写,同时也易于机器解析和生成(网络传输速率). GSON是由谷歌官方推出的 JSON 与 Java 对象转化的 Java类库 fast-json 阿里推