关于gson的解析
来源:互联网 发布:linux内核进程调度 编辑:程序博客网 时间:2024/05/01 14:59
Gson是Google提供的方便在json数据和Java对象之间转化的类库。 Gson地址
Gson
这是使用Gson的主要类,使用它时一般先创建一个Gson实例,然后调用toJson(Object)或者from(String,Class)方法进行转换。
- package com.example.gson;
- import com.google.gson.annotations.Expose;
- import com.google.gson.annotations.SerializedName;
- import java.util.Date;
- /**
- * Student 实体类
- * Created by liu on 13-11-25.
- */
- public class Student {
- int age;
- String name;
- @Expose(serialize = true,deserialize = false)
- @SerializedName("bir")
- Date birthday;
- public Student(int age, String name, Date birthday) {
- this.age = age;
- this.name = name;
- this.birthday = birthday;
- }
- public Student(int age, String name) {
- this.age = age;
- this.name = name;
- }
- @Override
- public String toString() {
- if (birthday == null) {
- return "{\"name\":" + name + ", \"age\":" + age + "}";
- } else {
- return "{\"name\":" + name + ", \"age\":" + age + ", \"birthday\":" + birthday.toString() + "}";
- }
- }
- }
使用Gson前先创建Gson对象。
- //首先创建Gson实例
- Gson gson = new Gson();
1. toJson,fromJson 简单对象之间的转化
- Student student = new Student(11, "liupan");
- String jsonStr = gson.toJson(student, Student.class);
- Log.e("Object to jsonStr", jsonStr);
- Student student1 = gson.fromJson(jsonStr, Student.class);
- Log.e("jsonStr to Object", student1.toString());
2 List 类型和JSON字符串之间的转换
- Student student11 = new Student(11, "liupan11");
- Student student12 = new Student(12, "liupan12");
- Student student13 = new Student(13, "liupan13");
- Stack<Student> list = new Stack<Student>();
- list.add(student11);
- list.add(student12);
- list.add(student13);
toJson
- String listJsonStr = gson.toJson(list);
- Log.e("list to jsonStr", listJsonStr);
fromJson
- Stack<Student> list2 = gson.fromJson(listJsonStr, new TypeToken<Stack<Student>>() {
- }.getType());
- Log.e("jsonStr to list", list2.toString());
0 0
- 关于gson的解析
- 关于Gson解析Json的问题
- 关于Gson解析Json的问题
- 关于Gson解析Json的问题
- 关于Gson和XML的解析方式
- 关于Gson泛型解析的解决方案。
- 关于Gson解析泛型的
- 关于Gson 解析出问题
- 关于使用Gson解析entity中遇到的问题
- 关于Gson解析复杂类型的json数据
- android-关于Gson和json的解析转化使用
- gson解析的案例
- Gson数据的解析。
- Gson的数据解析
- GSON解析的学习
- GSON解析的学习
- Gson的解析
- 关于Gson的使用
- UIReferenceLibraryViewController:App中字典词义查询的实现
- Linux下vsftpd配置
- excel中自动填充到最后一行
- Unity中将类对象保存到XML中
- Java Socket实战之三 传输对象
- 关于gson的解析
- 揭秘Android App的工作原理-乐居猫学Android开发
- 【codeforces】2014-2015ACM-ICPC CERC 14 Problem J: Pork barrel 【LCT+主席树】
- HDU 4487 Maximum Random Walk 概率DP
- 生活中的磨难
- 空指针、void*指针、new及delete
- Python中的matplotlib用法(转载)
- MAC 设置环境变量path的几种方法
- html5中的number