位置: 编程技术 - 正文

Google -gson 最全的文档(google gsoc)

编辑:rootadmin
Gson User Guide

推荐整理分享Google -gson 最全的文档(google gsoc),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:google organic,谷歌gsc,google-glog,google gsuit,google gsuit,google gsuit,google gsoc,google gsoc,内容如对您有帮助,希望把文章链接给更多的朋友!

Authors: Inderjeet Singh, Joel Leitch, Jesse Wilson

Overview

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson is an open-source project hosted at can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Goals for GsonProvide easy to use mechanisms like toString() and constructor (factory method) to convert Java to JSON and vice-versaAllow pre-existing unmodifiable objects to be converted to and from JSONAllow custom representations for objectsSupport arbitrarily complex objectGenerate compact and readability JSON outputGson Users

Gson was originally created for use inside Google where it is currently used in a number of projects. It is now used by a number of public projects and companies. See details here.

Using Gson

The primary class to use is Gson which you can just create by calling new Gson(). There is also a class GsonBuilder available that can be used to create a Gson instance with various settings like version control and so on.

The Gson instance does not maintain any state while invoking Json operations. So, you are free to reuse the same object for multiple Json serialization and deserialization operations.

Primitives ExamplesObject Examples

Note that you can not serialize objects with circular references since that will result in infinite recursion.

Array Examples

We also support multi-dimensional arrays, with arbitrarily complex element types

Collections ExamplesSerializing and Deserializing Generic Types

When you call toJson(obj), Gson calls obj.getClass()to get information on the fields to serialize. Similarly, you can typically pass MyClass.classobject in the fromJson(json, MyClass.class) method. This works fine if the object is a non-generic type. However, if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure. Here is an example illustrating the point:

The above code fails to interpret value as type Bar because Gson invokes list.getClass() to get its class information, but this method returns a raw class, Foo.class. This means that Gson has no way of knowing that this is an object of type Foo, and not just plain Foo.

You can solve this problem by specifying the correct parameterized type for your generic type. You can do this by using the TypeToken class.

The idiom used to get fooTypeactually defines an anonymous local inner class containing a method getType()that returns the fully parameterized type.

Serializing and Deserializing Collection with Objects of Arbitrary Types

Sometimes you are dealing with JSON array that contains mixed types. For example: ['hello',5,{name:'GREETINGS',source:'guest'}]

The equivalent Collection containing this is:

Where the Event class is defined as:

You can serialize the collection with Gson without doing anything specific: toJson(collection)would write out the desired output. However, deserialization with fromJson(json, Collection.class) will not work since Gson has no way of knowing how to map the input to the types. Gson requires that you provide a genericised version of collection type in fromJson. So, you have three options:

Custom Serialization and Deserialization

Sometimes default representation is not what you want. This is often the case when dealing with library classes (DateTime, etc).

Gson allows you to register your own custom serializers and deserializers. This is done by defining two parts: Json Serialiers: Need to define custom serialization for an objectJson Deserializers: Needed to define custom deserialization for a typeInstance Creators: Not needed if no-args constructor is available or a deserializer is registered

registerTypeAdapter call checks if the type adapter implements more than one of these interfaces and register it for all of them.

Writing a Serializer

Here is an example of how to write a custom serializer for JodaTime DateTime class.

Gson calls toJson() when it runs into a DateTime object during serialization.

Writing a Deserializer

Here is an example of how to write a custom deserializer for JodaTime DateTime class.

Finer points with Serializers and Deserializers

Often you want to register a single handler for all generic types corresponding to a raw type For example, suppose you have an “Id” class for Id representation/translation (i.e. an internal vs. external representation). Id type that has same serialization for all generic types Essentially write out the id value Deserialization is very similar but not exactly the same

Need to call “new Id(Class, String)” which returns an instance of Id Gson supports registering a single handler for this. You can also register a specific handler for a specific generic type (say Id needed special handling). The Type parameter for the toJson and fromJson contains the generic type information to help you write a single handler for all generic types corresponding to the same raw type

Writing an Instance Creator

While deserializing an Object, Gson needs to create a default instance of the class Well-behaved classes that are meant for serialization and deserialization should have a no-argument constructor Doesn’t matter whether public or private Typically, Instance Creators are needed when you are dealing with a library class that does NOT define a no-argument constructor

Instance Creator ExampleGoogle -gson 最全的文档(google gsoc)

Type could be of a corresponding generic type Very useful to invoke constructors which need specific generic type information For example, if the Id class stores the class for which the Id is being created

InstanceCreator for a Parameterized Type

Sometimes that the type that you are trying to instantiate is a parameterized type. Generally, this is not a problem since the actual instance is of raw type. Here is an example:

In the above example, an instance of the Id class can not be created without actually passing in the actual type for the parameterized type. We solve this problem by using the passed method parameter, type. The type object in this case is the Java parameterized type representation of Id where the actual instance should be bound to Id. Since Id class has just one parameterized type parameter, T, we use the zeroth element of the type array returned by getActualTypeArgument() which will hold Foo.class in this case.

Compact Vs. Pretty Printing for JSON Output Format

The default JSON output that is provide by Gson is a compact JSON format. This means that there will not be any whitespace in the output JSON structure. Therefore, there will be no whitespace between field names and its value, object fields, and objects within arrays in the JSON output. As well, “null” fields will be ignored in the output (NOTE: null values will still be included in collections/arrays of objects). See the Null Object Support section for information on configure Gson to output all null values.

If you like to use the Pretty Print feature, you must configure your Gson instance using the GsonBuilder. The JsonFormatter is not exposed through our public API, so the client is unable to configure the default print settings/margins for the JSON output. For now, we only provide a default JsonPrintFormatter that has default line length of character, 2 character indentation, and 4 character right margin.

The following is an example shows how to configure a Gson instance to use the default JsonPrintFormatter instead of the JsonCompactFormatter:

Null Object Support

The default behaviour that is implemented in Gson is that null object fields are ignored. This allows for a more compact output format; however, the client must define a default value for these fields as the JSON format is converted back into its Java.

Here’s how you would configure a Gson instance to output null:

NOTE: when serializing nulls with Gson, it will add a JsonNull element to the JsonElement structure. Therefore, this object can be used in custom serialization/deserialization.

Here’s an example:

Versioning Support

Multiple versions of the same object can be maintained by using @Since annotation. This annotation can be used on Classes, Fields and, in a future release, Methods. In order to leverage this feature, you must configure your Gson instance to ignore any field/object that is greater than some version number. If no version is set on the Gson instance then it will serialize and deserialize all fields and classes regardless of the version.

Excluding Fields From Serialization and Deserialization

Gson supports numerous mechanisms for excluding top-level classes, fields and field types. Below are pluggable mechanism that allow field and class exclusion. If none of the below mechanism satisfy your needs then you can always use custom serializers and deserializers.

Java Modifier Exclusion

By default, if you mark a field as transient, it will be excluded. As well, if a field is marked as “static” then by default it will be excluded. If you want to include some transient fields then you can do the following:

NOTE: you can use any number of the Modifier constants to “excludeFieldsWithModifiers” method. For example:

This feature provides a way where you can mark certain fields of your objects to be excluded for consideration for serialization and deserialization to JSON. To use this annotation, you must create Gson by using new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(). The Gson instance created will exclude all fields in a class that are not marked with @Expose annotation.

User Defined Exclusion Strategies

If the above mechanisms for excluding fields and class type do not work for you then you can always write your own exclusion strategy and plug it into Gson. See the ExclusionStrategy JavaDoc for more information.

The following example shows how to exclude fields marked with a specific “@Foo” annotation and excludes top-level types (or declared field type) of class String.

JSON Field Naming Support

Gson supports some pre-defined field naming policies to convert the standard Java field names (i.e. camel cased names starting with lower case — “sampleFieldNameInJava”) to a Json field name (i.e. sample_field_name_in_java or SampleFieldNameInJava). See the FieldNamingPolicy class for information on the pre-defined naming policies.

It also has an annotation based strategy to allows clients to define custom names on a per field basis. Note, that the annotation based strategy has field name validation which will raise “Runtime” exceptions if an invalid field name is provided as the annotation value.

The following is an example of how to use both Gson naming policy features:

If you have a need for custom naming policy (see this discussion), you can use the @SerializedName annotation.

Sharing State Across Custom Serializers and Deserializers

Sometimes you need to share state across custom serializers/deserializers (see this discussion). You can use the following three strategies to accomplish this: Store shared state in static fields Declare the serializer/deserializer as inner classes of a parent type, and use the instance fields of parent type to store shared state Use Java ThreadLocal 1 and 2 are not thread-safe options, but 3 is.

Streaming

In addition Gson’s object model and data binding, you can use Gson to read from and write to a stream. You can also combine streaming and object model access to get the best of both approaches.

Issues in Designing Gson

See the Gson design document for a discussion of issues we faced while designing Gson. It also include a comparison of Gson with other Java libraries that can be used for Json conversion.

Future Enhancements to Gson

For the latest list of proposed enhancements or if you’d like to suggest new ones, see the Issues section under the project website.

木瓜妮子多媒体开发教程---第一天---Android环境搭建和Helloworld项目测试 Android环境搭建写在前面的话:虽然开通博客已经很久了,但是始终没有时间来整理和总结心得,今天终于忙里抽闲的把自己近一个月完成的多个APP原型

初次使用LogCat遇到的问题 1.怎样打开logcat:eclipse-Window-ShowView-Other-Android-LogCat。2.有时候LogCat不显示日志信息,个人搜索了一下没发现什么有效办法,一般都是简单地重启eclipse,

TextView_跑马灯效果 本文实现了android系统自带的跑马灯效果(marquee)与自定义的跑马灯效果的对比。1.在系统自带的跑马灯中,xml布局文件必须配置的属性有以下几个:(1

标签: google gsoc

本文链接地址:https://www.jiuchutong.com/biancheng/381040.html 转载请保留说明!

上一篇:Android网络开发-URL(android网络开发技术答案形考任务五)

下一篇:木瓜妮子多媒体开发教程---第一天---Android环境搭建和Helloworld项目测试(木瓜电子)

  • 小规模纳税人每月不超过10万
  • 公司附加税怎么计算
  • 会计工资标准
  • 资产减值损失借方表示
  • 小规模纳税人开票税率
  • 开发票要多交费正常吗?
  • 公司税务状态变更怎么办
  • 房地产企业拆迁补偿契税政策
  • 专项资金是否缴纳企业所得税
  • 两个公司的现金怎么交税
  • 未认缴出资的股东退股
  • 福利企业退税的资金去处
  • 小企业准则适用范围
  • 出口当月开票当月申报吗
  • 物业公司营改增税务筹划方案
  • 案例分析个人心得体会
  • 企业劳务外包取费的标准以及依据是什么?
  • 2019年基金市场
  • 年初未交增值税借方怎么处理
  • 电池消费税征税范围
  • 来料加工出口退税申报操作
  • 增值税专用发票税号错误
  • 电脑管家游戏加速怎么卸载
  • 会计差错更正账务处理 对股价影响
  • 利润为负数怎么调
  • 企业开票附加税
  • win7旗舰版分辨率调高了黑屏怎么办
  • 资产处置收益与固定资产清理
  • 差额发票可以开1个点吗?
  • 差额征税通俗理解
  • php版本常用的排版软件
  • le启动exe是什么意思
  • 未实缴出资的股权转让后还要承担法律后果吗
  • 运输发票符合什么要求
  • 增值税专用发票几个点
  • 购货人与收货人的关系
  • 最小的外置dvd刻机多少寸
  • 研发费用如何加计扣除何时申报
  • 计提的增值税可以扣除吗
  • php操作mysql数据库的扩展有哪三个
  • 数据库读写异常
  • php 数组
  • php书籍读后感
  • php公众号开发框架
  • 新企业所得税季初资产总额怎么填
  • 利息收入怎么做账务处理
  • 外籍专家劳务费
  • 外请专家讲课费如何交税
  • 预付账款的适用范围
  • php.ini上传限制
  • distinct用法及搭配
  • 水电费进项税额转出情形
  • 营改增后房屋租赁税变化
  • 电子税务局没有增值税申报怎么办?
  • 进项税准予抵扣条件有哪些
  • 拍卖行业收取手续费多少
  • 红冲发票重开一定要一样的金额吗?
  • 以前年度生产成本怎么转为研发费用
  • 小规模企业自开收购牛发票增值税怎样申报
  • 会计制度和会计准则科目转换
  • 房地产企业收入确认条件税法
  • 实际利率 会计
  • 政府机关有纳税人吗
  • mysql的索引实现原理
  • securedownload是什么意思
  • 如何使用u盘安装软件
  • .exe是啥程序
  • 合并多个js文件
  • bat批量处理
  • unity3d性能优化之贴图科普篇
  • shell脚本运行linux命令
  • 在vue中添加按钮使内容消失
  • jquery 上传进度
  • js函数全局变量
  • 告诉你什么是无限的恐怖日语
  • 广西国家税务总局电子税务局官网
  • 企业登录初始密码
  • 千元版的发票
  • 加强税务系统党委全面监督工作
  • 重庆国税电子税务登录
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设