通透[email protected]注解、@SerializedName、解析json数据

在讲如何解析数据之前,先描述一下gson中的两个注解@Expose和@SerializedName。

@Expose注解的作用:区分实体中不想被序列化的属性,其自身包含两个属性deserialize(反序列化)和serialize(序列化),默认都为true。

使用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();创建Gson对象,没有@Expose注释的属性将不会被序列化.。

private class User{
      private int id;
      @Expose
      private String name;
      .......

}

这样create() gson对象序列化user,只会有name这一个属性

@SerializedName注解的作用:定义属性序列化后的名称

public class User{
     private int id;
     @Expose
     @SerializedName("username")
     private String name;
     .......

}

另外想要不序列化某个属性,也可以使用transient。

private class User{
      private int id;
      private transient String name;
      .......

}

下面列举一下gson如何解析json数据的

//转换器
GsonBuilder builder = new GsonBuilder();
<span style="color:#ff0000;">// 不转换没有 @Expose 注解的字段</span>
builder.excludeFieldsWithoutExposeAnnotation();
Gson gson = builder.create();
<span style="color:#ff0000;">//1、对象转string</span>
Student stu = new Student();
stu.setStudentId(333);
stu.setStudentName("qqq");
String stuStr = gson.toJson(stu);
System.out.println(stuStr); //{"studentName":"qqq","studentId":333}
<span style="color:#ff0000;">//2、string转对象</span>
Student user2 = gson.fromJson(stuStr, Student.class);
System.out.println(user2);
String stuTemp = "{\"studentName\":\"qqq2\",\"studentId\":3335}";
Student user4 = gson.fromJson(stuTemp, Student.class);
System.out.println(user4);
<span style="color:#ff0000;">//3、对象List转string</span>
List<Student> testBeanList = new ArrayList<Student>();
Student testBean = new Student();
testBean.setStudentId(555);
testBean.setStudentName("552");
testBeanList.add(testBean);
//Gson gsonList = new Gson();
Type type = new TypeToken<List<Student>>(){}.getType(); //指定集合对象属性
String beanListToJson = gson.toJson(testBeanList, type);
System.out.println(beanListToJson); //[{"studentName":"552","studentId":555}]
<span style="color:#ff0000;">//集合string转对象list</span>
List<Student> testBeanListFromJson = gson.fromJson(beanListToJson, type);
System.out.println(testBeanListFromJson); //[555:552]
<span style="color:#ff0000;">//4、集合如果不指定类型 默认为String</span>
List<String> testList = new ArrayList<String>();
testList.add("first");
testList.add("second");
String listToJson = gson.toJson(testList);
System.out.println(listToJson); //["first","second"]
<span style="color:#ff0000;">//5、集合字符串转回来需要指定类型</span>
List<String> testList2 = (List<String>) gson.fromJson(listToJson,new TypeToken<List<String>>() {}.getType());
System.out.println(testList2);
<span style="color:#ff0000;">//6、 将HashMap字符串转换为 JSON</span>
Map<String, String> testMap = new HashMap<String, String>();
testMap.put("id", "id.first");
testMap.put("name", "name.second");
String mapToJson = gson.toJson(testMap);
System.out.println(mapToJson); //{"id":"id.first","name":"name.second"}
<span style="color:#ff0000;">//7、stringMap转对象</span>
Map<String, String> userMap2 = (Map<String, String>) gson.fromJson(mapToJson,new TypeToken<Map<String, String>>() {}.getType());
System.out.println(userMap2); //{id=id.first, name=name.second}
<span style="color:#ff0000;">//8、对象含有普通对象、集合、map情况</span>
Student user1 = new Student();
user1.setStudentId(1001);
user1.setStudentName("张三");
Student user3 = new Student();
user3.setStudentId(1002);
user3.setStudentName("李四");
Map<String, Student> userMap = new HashMap<String, Student>();
userMap.put("user1", user1);
userMap.put("user3", user3);
List<Student> userList = new ArrayList<Student>();
userList.add(user1);
userList.add(user3);
Teacher groupBean = new Teacher();
groupBean.setStudent(user1);
groupBean.setStus(userList);
groupBean.setMap((HashMap)userMap);
//groupBean.setUserList(userList);
Gson gsonGroup = new Gson();
String sGroupBean = gsonGroup.toJson(groupBean, new TypeToken<Teacher>() {}.getType());
System.out.println(sGroupBean);
/*{"stus":[{"studentName":"张三","studentId":1001},{"studentName":"李四","studentId":1002}],"student":{"studentName":"张三","studentId":1001},"map":{"user3":{"studentName":"李四","studentId":1002},"user1":{"studentName":"张三","studentId":1001}},"id":0,"age":0}*/
<span style="color:#ff0000;">//9、复杂对象string转对象</span>
Teacher groupBean2 = (Teacher) gson.fromJson(sGroupBean,new TypeToken<Teacher>() {}.getType());
System.out.println(groupBean2);

package com.andtools;
import com.google.gson.annotations.Expose;
public class Student {
  @Expose
  private String studentName;
  @Expose
  private int studentId;
  public Student(){}
  public Student(int studentId,String studentName){
    this.setStudentId(studentId);
    this.setStudentName(studentName);
  }
  public String toString(){
    return this.getStudentId() + ":" + this.getStudentName();
  }
  public String getStudentName() {
    return studentName;
  }
  public void setStudentName(String studentName) {
   this.studentName = studentName;
  }
  public int getStudentId() {
   return studentId;
  }
  public void setStudentId(int studentId) {
   this.studentId = studentId;
  }
}

package com.andtools;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.annotations.Expose;
public class Teacher {
  @Expose
  private int id;
  @Expose
  private String name;
  @Expose
  private int age;
  @Expose
  private Student student;
  @Expose
  private List stus;
  @Expose
  private HashMap map;
  public String toString(){
    return this.getId()+":"+this.getName()+":"+this.getAge() +":"+ this.getStudent().toString() + ":" + this.getStus() + ":" + this.getMap();
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
   this.age = age;
  }
  public Student getStudent() {
    return student;
  }
  public void setStudent(Student student) {
    this.student = student;
  }
  public List getStus() {
    return stus;
  }
  public void setStus(List stus) {
    this.stus = stus;
  }
  public HashMap getMap() {
    return map;
  }
  public void setMap(HashMap map) {
    this.map = map;
  }
}
时间: 2024-10-10 00:27:27

通透[email protected]注解、@SerializedName、解析json数据的相关文章

springboot情操陶冶[email&#160;protected]注解解析

承接前文springboot情操陶冶[email protected]注解解析,本文将在前文的基础上对@SpringBootApplication注解作下简单的分析 @SpringBootApplication 该注解是springboot最集中的一个注解,也是应用最广泛的注解.官方也多用此注解以启动spring服务,我们看下其中的源码 @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Inher

[email&#160;protected]注解与自动装配

1   配置文件的方法 我们编写spring 框架的代码时候.一直遵循是这样一个规则:所有在spring中注入的bean 都建议定义成私有的域变量.并且要配套写上 get 和 set方法. Boss 拥有 Office 和 Car 类型的两个属性:       清单 3. Boss.java [java] view plaincopy package com.baobaotao; public class Boss { private Car car; private Office office

s[email&#160;protected]注解

自动将数据封装成json格式的数据返回回去 Maven <!-- Json Begin --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackso

springboot自动装配(1)[email&#160;protected]注解怎么自动装配各种组件

1.对于springboot个人认为它就是整合了各种组件,然后提供对应的自动装配和启动器(starter) [email protected]注解其实就是组合注解,通过它找到自动装配的注解@EnableAutoConfiguration,再由@EnableAutoConfiguration导入自动装配选择类AutoConfigurationImportSelector的selectImports方法去MATA-INF/spring.factories下面找到需要自动装配的组件的对应配置(各种Au

我的Android进阶之旅------&gt;解决Jackson、Gson解析Json数据时,Json数据中的Key为Java关键字时解析为null的问题

1.问题描述 首先,需要解析的Json数据类似于下面的格式: { ret: 0, msg: "normal return.", news: [ { id: "NEW2016062800875700", from: "腾讯新闻客户端", qqnews_download_url: "http://inews.qq.com/m?refer=openapi_for_xiaotiancai", articletype: "1&

Android网络之数据解析----使用Google Gson解析Json数据

[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/4063452.html 联系方式:[email protected] [正文] 文章回顾: Android网络之数据解析----SAX方式解析XML数据 一.Json数据的介绍                                                             

通过Gson解析Json数据

Json是一种数据格式,便于数据传输.存储.交换:Gson是一种组件库,可以把java对象数据转换成json数据格式. gson.jar的下载地址:http://search.maven.org/#search%7Cga%7C1%7Ca%3A%22gson%22 一.Json数据样式 为了便于理解我们先来看看Json的数据样式: 1. 单个数据对象 { "id": 100, "body": "It is my post", "numbe

JS解析Json 数据并跳转到一个新页面,取消A 标签跳转

JS解析Json 数据并跳转到一个新页面,代码如下 $.getJSON("http://api.cn.abb.com/common/api/staff/employee/" + obj.id, function (result) { window.open("https://abb-my.sharepoint.com/_layouts/15/me.aspx?p=" + result.Email, "_blank") }); 取消A 标签跳转 &l

Gson解析Json数据

在Android开发中就经常用到json解析,方便的是Google已经为我们提供了一个很棒的json解析库–gson. 以下是示例代码: /** * GSON解析JSON数据 * @author dream * */ public class TestGsonActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method