Gson [MavenDependency]といくつかの簡単な例



Gson



Mavne依存

 com.google.code.gson gson 2.2.4 

Gson jarパッケージのダウンロードアドレス:http://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.0/



Gsonのインスタンス化:

1:グソン gson = 新着 グソン()



2:GsonBuilderを介して複数のオプションを構成できます

[java] プレーンビュー コピー

印刷 コード



  1. gson = new GsonBuilder()
  2. .setLenient()// jsonルーズ
  3. .enableComplexMapKeySerialization()//マップのキーを複雑なオブジェクトの形式としてサポートします
  4. .serializeNulls()//スマートヌル
  5. .setPrettyPrinting()//チューニングフォーマット
  6. .disableHtmlEscaping()//デフォルトはHTMLをエスケープするためのGSONです
  7. .create()

Gsonの基本的な使用法:

Json文字列を変換するJavaBean

Gsonは提供しています 公衆 String toJson(Object src)メソッドは、オブジェクトをjsonStrに変換します

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. / **
  4. * @author xuanyouwu
  5. * @email root @ xxxxx
  6. * @time 2016-05-18 10:39
  7. * /
  8. パブリッククラスGsonTest1 {
  9. パブリック静的クラスStudent {
  10. プライベート文字列名
  11. プライベートint年齢
  12. //セッターゲッターが等しいを省略します
  13. }
  14. private static void log(String msg){
  15. System.out.println(msg)
  16. }
  17. public static void main(String [] args)は例外をスローします{
  18. Gson gson =新しいGson()
  19. 学生学生=新しい学生()
  20. student.setName( 'xuanyouwu')
  21. student.setAge(26)
  22. 文字列jsonStr = gson.toJson(学生)
  23. log( '----> javabean convert jsonStr:' + jsonStr)
  24. }
  25. }

演算結果:

----> javabean convert jsonStr:{'name': 'xuanyouwu'、 'age':26}

リストマップからJson文字列

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. java.util.Arraysをインポートします
  4. java.util.HashMapをインポートします
  5. java.util.Listをインポートします
  6. java.util.Mapをインポートします
  7. / **
  8. * @author xuanyouwu
  9. * @email root @ xxxxx
  10. * @time 2016-05-18 10:39
  11. * /
  12. パブリッククラスGsonTest1 {
  13. private static void log(String msg){
  14. System.out.println(msg)
  15. }
  16. public static void main(String [] args)は例外をスローします{
  17. Gson gson =新しいGson()
  18. リストリスト= Arrays.asList( '1'、 'a'、 '3'、 'rt'、 '5')
  19. log( '----> list convert jsonStr:' + gson.toJson(list))
  20. マップコンテンツ= new HashMap()
  21. content.put( 'name'、 'xuanyouwu')
  22. content.put( 'age'、 '26')
  23. log( '----> map convert jsonStr:' + gson.toJson(content))
  24. }
  25. }

[java] プレーンビュー コピー

印刷 コード

  1. 演算結果:

[java] プレーンビュー コピー

印刷 コード

  1. ----> list convert jsonStr:['1'、 'a'、 '3'、 'rt'、 '5']
  2. ----> map convert jsonStr:{'name': 'xuanyouwu'、 'age': '26'}

JavaBeanへのJson文字列

[java] プレーンビュー コピー

印刷 コード

  1. 文字列studentJsonStr = '{' name ':' xuanyouwu '、' age ':26}'
  2. 学生student1 = gson.fromJson(studentJsonStr、Student.class)
  3. log( '-------> json convert JavaBean:' + student1)


結果:

-------> json convert JavaBean:Student {name = 'xuanyouwu'、age = 26}

リストへのJson文字列

[java] プレーンビュー コピー

印刷 コード

  1. 文字列listJsonStr = '[' 1 '、' a '、' 3 '、' rt '、' 5 ']'

[java] プレーンビュー コピー

印刷 コード

  1. タイプtype = new TypeToken (){
  2. } .getType()
  3. ArrayList sList = gson.fromJson(listJsonStr、type)
  4. log( '-------> json convert List:' + sList)

[java] プレーンビュー コピー

印刷 コード

  1. 演算結果:

[java] プレーンビュー コピー

印刷 コード

  1. -------> json convert List:[1、a、3、rt、5]

[java] プレーンビュー コピー

印刷 コード

  1.  Gson-packaged type system

[java] view plain copy

print ?  CODE

  1. Gson has a very interesting abstract base class JsonElement, his inheritance system:

[java] view plain copy

print ?  CODE

[java] view plain copy

print ?  CODE

  1. JsonObject is equivalent to org's JSONObject, and JsonArray is similar.

[java] view plain copy

print ?  CODE

  1. JsonNull is actually a null field

[java] view plain copy

print ?  CODE

  1. JsonNull jsonNull=new JsonNull()//The construction method is outdated, recommend INSTANCE

[java] view plain copy

print ?  CODE

  1. JsonNull jsonNull=JsonNull.INSTANCE
  2. log('-----'+jsonNull)

[java] view plain copy

print ?  CODE

  1. operation result:

[java] view plain copy

print ?  CODE

  1. -----null

JsonPrimitive is very interesting. We know that if json is converted to a string, it may contain quotation marks, but with JsonPrimative we can get the escaped string, see the example:

[java] view plain copy

print ?  CODE

  1. package com.xuan.gson
  2. import com.google.gson.JsonNull
  3. import com.google.gson.JsonPrimitive
  4. /**
  5. * @author xuanyouwu
  6. * @email root@xxxxx
  7. * @time 2016-05-18 11:20
  8. */
  9. public class GsonTest2 {
  10. private static void log(String msg) {
  11. System.out.println(msg)
  12. }
  13. public static void main(String[] args) throws Exception {
  14. String studentJsonStr='{'name':'xuanyouwu','age':26}'
  15. log('------>studentJsonStr:'+studentJsonStr)
  16. JsonPrimitive jsonPrimitive=new JsonPrimitive(studentJsonStr)
  17. log('------>jsonPrimitive:'+jsonPrimitive)
  18. log('------>jsonPrimitive:'+jsonPrimitive.toString())
  19. log('------>jsonPrimitive:'+jsonPrimitive.getAsString())
  20. JsonPrimitive jsonPrimitive2=new JsonPrimitive('this is String')
  21. log('------>jsonPrimitive2:'+jsonPrimitive2)
  22. log('------>jsonPrimitive2:'+jsonPrimitive2.toString())
  23. log('------>jsonPrimitive2:'+jsonPrimitive2.getAsString())
  24. }
  25. }

operation result:

------>studentJsonStr:{'name':'xuanyouwu','age':26}
------>jsonPrimitive:'{'name':'xuanyouwu','age':26}'
------>jsonPrimitive:'{'name':'xuanyouwu','age':26}'
------>jsonPrimitive:{'name':'xuanyouwu','age':26}
------>jsonPrimitive2:'this is String'
------>jsonPrimitive2:'this is String'
------>jsonPrimitive2:this is String

Create a JsonObject

Add fields to jsonObject via addPropert(key,value) Similar to hashMap

[java] view plain copy

print ?  CODE

  1. JsonObject jsonObject=new JsonObject()
  2. jsonObject.addProperty('name','xuanyouwu')
  3. jsonObject.addProperty('age',26)
  4. log('------>create jsonObject:'+jsonObject)

operation result:

------>create jsonObject:{'name':'xuanyouwu','age':26}

Create a JsonArray

[java] view plain copy

print ?  CODE

  1. JsonArray jsonElements=new JsonArray()
  2. jsonElements.add('a')
  3. jsonElements.add('b')
  4. jsonElements.add('c')
  5. jsonElements.add('d')
  6. log('------>create jsonArray:'+jsonElements)

operation result:

------>create jsonArray:['a','b','c','d']

JsonObject nested array or nested JsonArray

Add an array of fields to jsonObject via JsonObject's add(key, JsonElement)

[java] view plain copy

print ?  CODE

  1. JsonObject jsonObject2=new JsonObject()
  2. jsonObject2.addProperty('name','xuanyouwu')
  3. jsonObject2.addProperty('age',26)
  4. JsonArray jsonElements2=new JsonArray()
  5. jsonElements2.add('riding')
  6. jsonElements2.add('playing game')
  7. jsonElements2.add('watching TV')
  8. jsonObject2.add('hobby',jsonElements2)
  9. log('------>create jsonObject inner JsonArray:'+jsonObject2)

operation result:

------>create jsonObject inner JsonArray:{'name':'xuanyouwu','age':26,'hobby':['cycling', 'playing games', 'watching TV']}

Gson annotation

There are five types of annotations in Gson

Rename annotation: SerializedName

Role: conversion keyword key, json converted to JavaBean, json field key must be the same as the field name of the class we declare, when the server returns the keyword how to do, such as the key is new switch, we are in the declaration class When you can't write such a field, you may want to change the server side, he may have to change database , but I tell you that most of the server is not willing to change his json, it is very selfish! This time the renaming annotations come in handy. The second scenario: the json key returned by the server is simply ugly, or Too long, you want to simplify, my_parent_name, can be simplified to mpn

Example:

[java] view plain copy

print ?  CODE

  1. package com.xuan.gson
  2. import com.google.gson.Gson
  3. import com.google.gson.annotations.SerializedName
  4. /**
  5. * @author xuanyouwu
  6. * @email root@xxxxx
  7. * @time 2016-05-18 11:20
  8. */
  9. public class GsonTest3 {
  10. private static void log(String msg) {
  11. System.out.println(msg)
  12. }
  13. public static class User {
  14. public String name
  15. public int age
  16. @SerializedName('new')
  17. public int isnew
  18. @Override
  19. public String toString() {
  20. return 'User{' +
  21. 'name='' + name + ''' +
  22. ', age=' + age +
  23. ', isnew=' + isnew +
  24. '}'
  25. }
  26. }
  27. public static void main(String[] args) throws Exception {
  28. String jsonFromServer = '{ ' +
  29. ' 'age': 26, ' +
  30. ' 'name': 'zhangsan', ' +
  31. ' 'new': 1 ' +
  32. '}'
  33. Gson gson = new Gson()
  34. User user = gson.fromJson(jsonFromServer, User.class)
  35. log('------>user:' + user)
  36. }
  37. }

Run result: ------>user:User{name='zhangsan', age=26, isnew=1}

[java] view plain copy

print ?  CODE

  1. package com.xuan.gson
  2. import com.google.gson.Gson
  3. import com.google.gson.annotations.SerializedName
  4. /**
  5. * @author xuanyouwu
  6. * @email root@xxxxx
  7. * @time 2016-05-18 11:20
  8. */
  9. public class GsonTest3 {
  10. private static void log(String msg) {
  11. System.out.println(msg)
  12. }
  13. public static class User2 {
  14. public String name
  15. public int age
  16. @SerializedName('my_parent_name')
  17. public String pn
  18. @Override
  19. public String toString() {
  20. return 'User2{' +
  21. 'name='' + name + ''' +
  22. ', age=' + age +
  23. ', pn='' + pn + ''' +
  24. '}'
  25. }
  26. }
  27. public static void main(String[] args) throws Exception {
  28. String jsonFromServer2='{ ' +
  29. ' 'age': 26, ' +
  30. ' 'my_parent_name': 'zhangsanf', ' +
  31. ' 'name': 'zhangsan' ' +
  32. '}'
  33. Gson gson2 = new Gson()
  34. User2 user2 = gson2.fromJson(jsonFromServer2, User2.class)
  35. log('------>user2:' + user2)
  36. }
  37. }

Run results: ------>user2:User2{name='zhangsan', age=26, pn='zhangsanf'}

Role 2: Combine alternate to provide multiple alternate field keys for parsing, @SerializedName(value = 'desc' ,alternate = { 'other' , 'note' }) If there is another in json, it will be parsed into desc. If there is a note, it will be parsed into desc. Note that the value in 1:value cannot appear in the alternate. Note that the alternative field of 2:alternate will be replaced by the previous one.

Example:

[java] view plain copy

print ?  CODE

  1. package com.xuan.gson
  2. import com.google.gson.Gson
  3. import com.google.gson.annotations.SerializedName
  4. /**
  5. * @author xuanyouwu
  6. * @email root@xxxxx
  7. * @time 2016-05-18 11:20
  8. */
  9. public class GsonTest4 {
  10. private static void log(String msg) {
  11. System.out.println(msg)
  12. }
  13. public static class User {
  14. public String name
  15. public int age
  16. @SerializedName(value = 'desc',alternate = {'other','note'})
  17. public String desc
  18. @Override
  19. public String toString() {
  20. return 'User{' +
  21. 'name='' + name + ''' +
  22. ', age=' + age +
  23. ', desc='' + desc + ''' +
  24. '}'
  25. }
  26. }
  27. public static void main(String[] args) throws Exception {
  28. String jsonFromServer = '{ ' +
  29. ' 'age': 26, ' +
  30. ' 'other': 'Chengdu people', ' +
  31. ' 'name': 'zhangsan' ' +
  32. '}'
  33. Gson gson = new Gson()
  34. User user = gson.fromJson(jsonFromServer, User.class)
  35. log('------>user:' + user)
  36. String jsonFromServer2 = '{ ' +
  37. ' 'age': 26, ' +
  38. ' 'note': 'Chengdu people', ' +
  39. ' 'name': 'zhangsan' ' +
  40. '}'
  41. User user2 = gson.fromJson(jsonFromServer2, User.class)
  42. log('------>user:' + user2)
  43. //Include desc and note note after desc
  44. String jsonFromServer3='{ ' +
  45. ' 'age': 26, ' +
  46. ' 'desc': 'desc Chengdu people', ' +
  47. ' 'name': 'zhangsan', ' +
  48. ' 'note': 'note Chengdu people' ' +
  49. '}'
  50. User user3 = gson.fromJson(jsonFromServer3, User.class)
  51. log('------>user:' + user3)
  52. //Include desc and note note before desc
  53. String jsonFromServer4='{ ' +
  54. ' 'age': 26, ' +
  55. ' 'note': 'note Chengdu people', ' +
  56. ' 'name': 'zhangsan', ' +
  57. ' 'desc': 'desc Chengdu people' ' +
  58. '}'
  59. User user4 = gson.fromJson(jsonFromServer4, User.class)
  60. log('------>user:' + user4)
  61. }
  62. }

operation result:

------>user:User{name='zhangsan', age=26, desc='Chengdu people'}
------>user:User{name='zhangsan', age=26, desc='Chengdu people'}
------>user:User{name='zhangsan', age=26, desc='note Chengdu people'}
------>user:User{name='zhangsan', age=26, desc='desc Chengdu people'}

Gson @Expose filter annotation

Source code: Default can be serialized or deserialized

[java] view plain copy

print ?  CODE

  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.FIELD)
  3. public @interface Expose {
  4. public boolean serialize() default true
  5. public boolean deserialize() default true
  6. }

[java] view plain copy

print ?  CODE

  1. can exclude fields that don't need to be serialized and need to be used with GsonBuilder

[java] view plain copy

print ?  CODE

  1.  Gson gson = new GsonBuilder ()
  2. .excludeFieldsWithoutExposeAnnotation()
  3. .create()
 Fields that do not add @Expose annotations will not be parsed:
 Divided into the following situations:
 1: Do not add @Expose annotation equivalent to @Expose(deserialize =  false ,serialize =  false ) do not do any analysis
 2:@Expose(deserialize =  true ,serialize =  false ) only parsing, that is, deserialization can be, serialization can not
 3:@Expose(deserialize =  false ,serialize =  true Serialization can, deserialization is not possible
 4:@Expose(deserialize =  true ,serialize =  true ) can be serialized or deserialized
 Example: These four cases will be demonstrated separately
 
 
 
  Do not add @Expose annotations : equivalent to @Expose(deserialize =  false ,serialize =  false )
 

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. com.google.gson.GsonBuilderをインポートします
  4. / **
  5. * @author xuanyouwu
  6. * @email root @ xxxxx
  7. * @time 2016-05-18 11:20
  8. * /
  9. パブリッククラスGsonTest5 {
  10. private static void log(String msg){
  11. System.out.println(msg)
  12. }
  13. public static class User {
  14. パブリック文字列名
  15. @オーバーライド
  16. public String toString(){
  17. 'User {' +を返します
  18. 'name =' '+ name +' '' +
  19. '}'
  20. }
  21. }
  22. public static void main(String [] args)は例外をスローします{
  23. 文字列jsonFromServer = '{' name ':' zhangsan '}'
  24. Gson gson = new GsonBuilder()
  25. .excludeFieldsWithoutExposeAnnotation()
  26. .create()
  27. ユーザーuser = gson.fromJson(jsonFromServer、User.class)
  28. Log( '------>逆シリアル化:' +ユーザー)
  29. ユーザーuser1 = new User()
  30. user1.name = 'zhangsan2'
  31. 文字列userStr = gson.toJson(user1)
  32. Log( '------>シリアル化:' + userStr)
  33. }
  34. }
 operation result:
 ------>Deserialization: User{name='null'} ------>Serialization:{} 
  Add @Expose annotation  
 

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. com.google.gson.GsonBuilderをインポートします
  4. インポートcom.google.gson.annotations.Expose
  5. / **
  6. * @author xuanyouwu
  7. * @email root @ xxxxx
  8. * @time 2016-05-18 11:20
  9. * /
  10. パブリッククラスGsonTest5 {
  11. private static void log(String msg){
  12. System.out.println(msg)
  13. }
  14. public static class User {
  15. @Expose //は@Expose(deserialize = true、serialize = true)と同等です
  16. パブリック文字列名
  17. @オーバーライド
  18. public String toString(){
  19. 'User {' +を返します
  20. 'name =' '+ name +' '' +
  21. '}'
  22. }
  23. }
  24. public static void main(String [] args)は例外をスローします{
  25. 文字列jsonFromServer = '{' name ':' zhangsan '}'
  26. Gson gson = new GsonBuilder()
  27. .excludeFieldsWithoutExposeAnnotation()
  28. .create()
  29. ユーザーuser = gson.fromJson(jsonFromServer、User.class)
  30. Log( '------>逆シリアル化:' +ユーザー)
  31. ユーザーuser1 = new User()
  32. user1.name = 'zhangsan2'
  33. 文字列userStr = gson.toJson(user1)
  34. Log( '------>シリアル化:' + userStr)
  35. }
  36. }

演算結果:

------>逆シリアル化:User {name = 'zhangsan'}
------>シリアル化:{'name': 'zhangsan2'}

@Exposeアノテーションはシリアル化のみ

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. com.google.gson.GsonBuilderをインポートします
  4. インポートcom.google.gson.annotations.Expose
  5. / **
  6. * @author xuanyouwu
  7. * @email root @ xxxxx
  8. * @time 2016-05-18 11:20
  9. * /
  10. パブリッククラスGsonTest5 {
  11. private static void log(String msg){
  12. System.out.println(msg)
  13. }
  14. public static class User {
  15. @Expose(deserialize = false、serialize = true)
  16. パブリック文字列名
  17. @オーバーライド
  18. public String toString(){
  19. 'User {' +を返します
  20. 'name =' '+ name +' '' +
  21. '}'
  22. }
  23. }
  24. public static void main(String [] args)は例外をスローします{
  25. 文字列jsonFromServer = '{' name ':' zhangsan '}'
  26. Gson gson = new GsonBuilder()
  27. .excludeFieldsWithoutExposeAnnotation()
  28. .create()
  29. ユーザーuser = gson.fromJson(jsonFromServer、User.class)
  30. Log( '------>逆シリアル化:' +ユーザー)
  31. ユーザーuser1 = new User()
  32. user1.name = 'zhangsan2'
  33. 文字列userStr = gson.toJson(user1)
  34. Log( '------>シリアル化:' + userStr)
  35. }
  36. }

演算結果:

------>逆シリアル化:User {name = 'null'} ------>シリアル化:{'name': 'zhangsan2'}

@Exposeは逆シリアル化のみ

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. com.google.gson.GsonBuilderをインポートします
  4. インポートcom.google.gson.annotations.Expose
  5. / **
  6. * @author xuanyouwu
  7. * @email root @ xxxxx
  8. * @time 2016-05-18 11:20
  9. * /
  10. パブリッククラスGsonTest5 {
  11. private static void log(String msg){
  12. System.out.println(msg)
  13. }
  14. public static class User {
  15. @Expose(deserialize = true、serialize = false)
  16. パブリック文字列名
  17. @オーバーライド
  18. public String toString(){
  19. 'User {' +を返します
  20. 'name =' '+ name +' '' +
  21. '}'
  22. }
  23. }
  24. public static void main(String [] args)は例外をスローします{
  25. 文字列jsonFromServer = '{' name ':' zhangsan '}'
  26. Gson gson = new GsonBuilder()
  27. .excludeFieldsWithoutExposeAnnotation()
  28. .create()
  29. ユーザーuser = gson.fromJson(jsonFromServer、User.class)
  30. Log( '------>逆シリアル化:' +ユーザー)
  31. ユーザーuser1 = new User()
  32. user1.name = 'zhangsan2'
  33. 文字列userStr = gson.toJson(user1)
  34. Log( '------>シリアル化:' + userStr)
  35. }
  36. }

演算結果:

------>逆シリアル化:User {name = 'zhangsan'}
------>シリアル化:{}

@Since(float v)アノテーション バージョン管理

GsonBuilder.setVersion(n)と組み合わせると、n> = vのときにシリアル化されます。

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. com.google.gson.GsonBuilderをインポートします
  4. com.google.gson.annotations.Sinceをインポートします
  5. / **
  6. * @author xuanyouwu
  7. * @email root @ xxxxx
  8. * @time 2016-05-18 11:20
  9. * /
  10. パブリッククラスGsonTest6 {
  11. private static void log(String msg){
  12. System.out.println(msg)
  13. }
  14. public static class User {
  15. @Since(2)
  16. パブリック文字列名
  17. @オーバーライド
  18. public String toString(){
  19. 'User {' +を返します
  20. 'name =' '+ name +' '' +
  21. '}'
  22. }
  23. }
  24. public static void main(String [] args)は例外をスローします{
  25. 文字列jsonFromServer = '{' name ':' zhangsan '}'
  26. Gson gson = new GsonBuilder()
  27. .setVersion(1)//バージョン1
  28. .create()
  29. ユーザーuser1 = gson.fromJson(jsonFromServer、User.class)
  30. Log( '------> Deserialization v = 1:' + user1)
  31. ユーザーuser1_1 = new User()
  32. user1_1.name = 'zhangsan2'
  33. 文字列userStr = gson.toJson(user1_1)
  34. Log( '------> serialization v = 1:' + userStr)
  35. Gson gson2 =新しいGsonBuilder()
  36. .setVersion(2)//バージョン2です
  37. .create()
  38. ユーザーuser2 = gson2.fromJson(jsonFromServer、User.class)
  39. Log( '------>逆シリアル化v = 2:' + user2)
  40. ユーザーuser2_1 = new User()
  41. user2_1.name = 'zhangsan2'
  42. 文字列userStr2_1 = gson2.toJson(user2_1)
  43. Log( '------> serialization v = 2:' + userStr2_1)
  44. Gson gson3 =新しいGsonBuilder()
  45. .setVersion(3)//バージョンは3です
  46. .create()
  47. ユーザーuser3 = gson3.fromJson(jsonFromServer、User.class)
  48. Log( '------> Deserialization v = 3:' + user3)
  49. ユーザーuser3_1 = new User()
  50. user3_1.name = 'zhangsan2'
  51. 文字列userStr3_1 = gson3.toJson(user3_1)
  52. Log( '------> serialization v = 3:' + userStr3_1)
  53. }
  54. }

演算結果:

------>逆シリアル化v = 1:User {name = 'null'}
------>シリアル化v = 1:{}
------>逆シリアル化v = 2:User {name = 'zhangsan'}
------>シリアル化v = 2:{'name': 'zhangsan2'}
------>逆シリアル化v = 3:User {name = 'zhangsan'}
------>シリアル化v = 3:{'name': 'zhangsan2'}

@Util(float v)アノテーションバージョン管理

gsonのsetVersion(n)nのときに解析されます

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. com.google.gson.GsonBuilderをインポートします
  4. com.google.gson.annotations.Untilをインポートします
  5. / **
  6. * @author xuanyouwu
  7. * @email root @ xxxxx
  8. * @time 2016-05-18 11:20
  9. * /
  10. パブリッククラスGsonTest6 {
  11. private static void log(String msg){
  12. System.out.println(msg)
  13. }
  14. public static class User {
  15. @Until(2)
  16. パブリック文字列名
  17. @オーバーライド
  18. public String toString(){
  19. 'User {' +を返します
  20. 'name =' '+ name +' '' +
  21. '}'
  22. }
  23. }
  24. public static void main(String [] args)は例外をスローします{
  25. 文字列jsonFromServer = '{' name ':' zhangsan '}'
  26. Gson gson = new GsonBuilder()
  27. .setVersion(1)//バージョン1
  28. .create()
  29. ユーザーuser1 = gson.fromJson(jsonFromServer、User.class)
  30. Log( '------> Deserialization v = 1:' + user1)
  31. ユーザーuser1_1 = new User()
  32. user1_1.name = 'zhangsan2'
  33. 文字列userStr = gson.toJson(user1_1)
  34. Log( '------> serialization v = 1:' + userStr)
  35. Gson gson2 =新しいGsonBuilder()
  36. .setVersion(2)//バージョン2です
  37. .create()
  38. ユーザーuser2 = gson2.fromJson(jsonFromServer、User.class)
  39. Log( '------>逆シリアル化v = 2:' + user2)
  40. ユーザーuser2_1 = new User()
  41. user2_1.name = 'zhangsan2'
  42. 文字列userStr2_1 = gson2.toJson(user2_1)
  43. Log( '------> serialization v = 2:' + userStr2_1)
  44. Gson gson3 =新しいGsonBuilder()
  45. .setVersion(3)//バージョンは3です
  46. .create()
  47. ユーザーuser3 = gson3.fromJson(jsonFromServer、User.class)
  48. Log( '------> Deserialization v = 3:' + user3)
  49. ユーザーuser3_1 = new User()
  50. user3_1.name = 'zhangsan2'
  51. 文字列userStr3_1 = gson3.toJson(user3_1)
  52. Log( '------> serialization v = 3:' + userStr3_1)
  53. }
  54. }


結果:

------>逆シリアル化v = 1:User {name = 'zhangsan'}
------>シリアル化v = 1:{'name': 'zhangsan2'}
------>逆シリアル化v = 2:User {name = 'null'}
------>シリアル化v = 2:{}
------>逆シリアル化v = 3:User {name = 'null'}
------>シリアル化v = 3:{}

Gsonの高度な使用法

retrofit2.0のソースコードを見た学生は、使用法の中にGsonConverterFactoryがあることを知っていると思います。ここにソースコードがあります。

TypeAdapterを使用する方が効率的だと言われていますが、比較していません テスト 一時リリース後、TypeAdapterとは何ですか?

ソースコードの注釈は変換します Java JSONとの間のオブジェクトは、オブジェクトjson間の変換です。 Tジェネリッククラスのシリアル化と逆シリアル化を置き換えるロジック。

ソースコードから、2.1バージョンの前後の使用法を確認できます。 2.1バージョンより前では、アダプターをカスタマイズできます。

[java] プレーンビュー コピー

印刷 コード

  1. パブリッククラスPointAdapterはTypeAdapterを拡張します{
  2. * public Point read(JsonReader reader)はIOExceptionをスローします{
  3. * if(reader.peek()== JsonToken.NULL){
  4. * reader.nextNull()
  5. * nullを返す
  6. *}
  7. *文字列xy = reader.nextString()
  8. * String [] parts = xy.split( '、')
  9. * int x = Integer.parseInt(parts [0])
  10. * int y = Integer.parseInt(parts [1])
  11. *新しいPoint(x、y)を返します
  12. *}
  13. * public void write(JsonWriter writer、Point value)はIOException {をスローします
  14. * if(value == null){
  15. * writer.nullValue()
  16. *戻る
  17. *}
  18. *文字列xy = value.getX()+ '、' + value.getY()
  19. * writer.value(xy)
  20. *}
  21. *}}

使用する

[java] プレーンビュー コピー

印刷 コード

  1. GsonBuilderビルダー=新しいGsonBuilder()
  2. * builder.registerTypeAdapter(Point.class、new PointAdapter())
  3. * // PointAdapterが読み取り/書き込みメソッドでnullをチェックしなかった場合は、代わりに使用する必要があります
  4. * // builder.registerTypeAdapter(Point.class、new PointAdapter()。nullSafe())
  5. *..。
  6. * Gson gson = builder.create()

バージョン2.1の直後にジェネリックを挿入することをお勧めします。

 

[java] プレーンビュー コピー

印刷 コード

  1. // String json = '{' origin ':' 0,0 '、' points ':[' 1,2 '、' 3,4 ']}'
  2. // TypeAdapter graphAdapter = gson.getAdapter(Graph.class)
  3. //グラフグラフ= graphAdapter.fromJson(json)
  4. //}
  5. //そしてシリアル化の例:
     {@code 
  6. //
  7. // Graph graph = new Graph(...)
  8. // TypeAdapter graphAdapter = gson.getAdapter(Graph.class)
  9. // String json = graphAdapter.toJson(graph)
  10. // }
  Example: Using TypeAdapter to serialize and deserialize 
 

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. com.google.gson.TypeAdapterをインポートします
  4. / **
  5. * @author xuanyouwu
  6. * @email root @ xxxxx
  7. * @time 2016-05-18 11:20
  8. * /
  9. パブリッククラスGsonTest7 {
  10. private static void log(String msg){
  11. System.out.println(msg)
  12. }
  13. public static class User {
  14. パブリック文字列名
  15. public int age
  16. @オーバーライド
  17. public String toString(){
  18. 'User {' +を返します
  19. 'name =' '+ name +' '' +
  20. '、年齢=' +年齢+
  21. '}'
  22. }
  23. }
  24. public static void main(String [] args)は例外をスローします{
  25. Gson gson =新しいGson()
  26. TypeAdapter userTypeAdapter = gson.getAdapter(User.class)
  27. ユーザーuser = new User()
  28. user.name = 'xuanyouwu'
  29. user.age = 26
  30. 文字列userJsonStr = userTypeAdapter.toJson(user)
  31. Log( '------>シリアル化:' + userJsonStr)
  32. ユーザーuser1 = userTypeAdapter.fromJson(userJsonStr)
  33. Log( '------>逆シリアル化:' + user1)
  34. }
  35. }

[java] プレーンビュー コピー

印刷 コード

  1. 演算結果:

[java] プレーンビュー コピー

印刷 コード

  1. ------>シリアル化:{'name': 'xuanyouwu'、 'age':26}
  2. ------>逆シリアル化:User {name = 'xuanyouwu'、age = 26}
 Gson's fault tolerance mechanism: 
 Why is it fault-tolerant, and declare the int type of age in the javaBean. What if the server returns '' an empty string? collapse?
 If the json format is not standardized, such as  {name=zhangsan,age:26,hobby=null} found that it is not a normal key value 
 Fault Tolerance Implementation 1:
 1: How to create Gson

[java] プレーンビュー コピー

印刷 コード

  1. gson = new GsonBuilder()
  2. .setLenient()// jsonルーズ
  3. .create()

2:JsonReaderを使用する

 JsonReader jsonReader = gson.newJsonReader(value.charStream())

[java] プレーンビュー コピー

印刷 コード

  1. jsonReader。setLenient(true)

3:カスタムTypeAdapter

4:アノテーションJsonAdapterを使用すると、カスタムアダプターでもあります

1.2フレームワークによってクラスとして分類され、基本的なjson大判仕様、キーと値のペアが標準ではない、複数引用符など、エラーなしで解析を停止しますが、関数は比較的弱いです

バグを解決できます

[java] プレーンビュー コピー

印刷

  1. com.google.gson.JsonSyntaxException:com.google.gson.stream.MalformedJsonException:JsonReader.setLenient(true)を使用して不正な形式のJSONを受け入れます

3、4は1つのカテゴリに分類され、すべてカスタムアダプタに属しますが、3はgsonにバインドされ、4は注釈とフィールドバインディングを使用します

例:

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. com.google.gson.GsonBuilderをインポートします
  4. インポートcom.google.gson.JsonParseException
  5. com.google.gson.TypeAdapterをインポートします
  6. com.google.gson.stream.JsonReaderをインポートします
  7. com.google.gson.stream.JsonWriterをインポートします
  8. java.io.IOExceptionをインポートします
  9. / **
  10. * @author xuanyouwu
  11. * @email root @ xxxxx
  12. * @time 2016-05-18 11:20
  13. * /
  14. パブリッククラスGsonTest8 {
  15. private static void log(String msg){
  16. System.out.println(msg)
  17. }
  18. public static class User {
  19. パブリック文字列名
  20. public int age
  21. @オーバーライド
  22. public String toString(){
  23. 'User {' +を返します
  24. 'name =' '+ name +' '' +
  25. '、年齢=' +年齢+
  26. '}'
  27. }
  28. }
  29. public static class UserTypeAdapter extends TypeAdapter {
  30. @オーバーライド
  31. public void write(JsonWriter out、User value)はIOException {をスローします
  32. out.beginObject()
  33. out.name( 'name')。value(value.name)
  34. out.name( 'age')。value(value.age)
  35. out.endObject()
  36. }
  37. @オーバーライド
  38. public User read(JsonReader in)はIOException {をスローします
  39. ユーザーuser = new User()
  40. in.beginObject()
  41. while(in.hasNext()){
  42. スイッチ(in.nextName()){
  43. ケース '名前':
  44. user.name = in.nextString()
  45. ブレーク
  46. ケース '年齢':
  47. {を試してください
  48. 文字列str = in.nextString()
  49. user.age = Integer.valueOf(str)
  50. } catch(例外e){
  51. }
  52. ブレーク
  53. }
  54. }
  55. in.endObject()
  56. リターンユーザー
  57. }
  58. }
  59. public static void main(String [] args)は例外をスローします{
  60. Gson gson =新しいGson()
  61. 文字列jsonStrFromServer = '{ n' +
  62. ''年齢 ':' '、 n' +
  63. '' name ':' zhangsan ' n' +
  64. '}'
  65. log( '-------> jsonFromServer:' + jsonStrFromServer)
  66. {を試してください
  67. ユーザーuser = gson.fromJson(jsonStrFromServer、User.class)
  68. Log( '------>デフォルトのGson解析:' +ユーザー)
  69. } catch(JsonParseException e){// java.lang.NumberFormatException:空の文字列
  70. Log( '------>デフォルトのGson解析例外:' + e)
  71. }
  72. Gson gson2 =新しいGsonBuilder()
  73. .registerTypeAdapter(User.class、new UserTypeAdapter())。create()
  74. {を試してください
  75. ユーザーuser2 = gson2.fromJson(jsonStrFromServer、User.class)
  76. Log( '------>カスタムアダプタの解析:' + user2)
  77. } catch(JsonParseException e){// java.lang.NumberFormatException:空の文字列
  78. Log( '------>カスタムアダプタの例外:' + e)
  79. }
  80. {を試してください
  81. UserTypeAdapter userTypeAdapter = new UserTypeAdapter()
  82. ユーザーuser3 = userTypeAdapter.fromJson(jsonStrFromServer)
  83. Log( '------>カスタムアダプタ解析2:' + user3)
  84. } catch(例外e){
  85. Log( '------>カスタムアダプタ例外2:' + e)
  86. }
  87. }
  88. }

演算結果:

-------> jsonFromServer:{
'年齢': ''、
'名前': '張山'
}
------>デフォルトのGson解析例外:com.google.gson.JsonSyntaxException:java.lang.NumberFormatException:空の文字列
------>カスタムアダプタの解析:User {name = 'zhangsan'、age = 0}
------>カスタムアダプタの解析2:User {name = 'zhangsan'、age = 0}

年齢は空の文字列であることがわかりますが、全体的な解析プロセスには影響しません。これはクライアントにとって非常に使いやすいものです。

注釈方法に基づくと、上記のアプローチは全体論的である傾向があり、注釈の方法はフィールドである傾向があります

[java] プレーンビュー コピー

印刷 コード

  1. パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. インポートcom.google.gson.JsonParseException
  4. com.google.gson.TypeAdapterをインポートします
  5. com.google.gson.annotations.JsonAdapterをインポートします
  6. com.google.gson.stream.JsonReaderをインポートします
  7. com.google.gson.stream.JsonWriterをインポートします
  8. java.io.IOExceptionをインポートします
  9. / **
  10. * @author xuanyouwu
  11. * @email root @ xxxxx
  12. * @time 2016-05-18 11:20
  13. * /
  14. パブリッククラスGsonTest9 {
  15. private static void log(String msg){
  16. System.out.println(msg)
  17. }
  18. public static class User {
  19. パブリック文字列名
  20. @JsonAdapter(IntegerTypeAdapter.class)
  21. public int age
  22. @オーバーライド
  23. public String toString(){
  24. 'User {' +を返します
  25. 'name =' '+ name +' '' +
  26. '、年齢=' +年齢+
  27. '}'
  28. }
  29. }
  30. public static class IntegerTypeAdapter extends TypeAdapter {
  31. @オーバーライド
  32. public void write(JsonWriter out、Integer value)はIOException {をスローします
  33. out.value(value)
  34. }
  35. @オーバーライド
  36. public Integer read(JsonReader in)はIOException {をスローします
  37. int i = 0
  38. {を試してください
  39. 文字列str = in.nextString()
  40. i = Integer.valueOf(str)
  41. } catch(例外e){
  42. }
  43. 私を返す
  44. }
  45. }
  46. パブリック静的クラスUser2 {
  47. パブリック文字列名
  48. public int age
  49. @オーバーライド
  50. public String toString(){
  51. 'User {' +を返します
  52. 'name =' '+ name +' '' +
  53. '、年齢=' +年齢+
  54. '}'
  55. }
  56. }
  57. public static void main(String [] args)は例外をスローします{
  58. Gson gson =新しいGson()
  59. 文字列jsonStrFromServer = '{ n' +
  60. ''年齢 ':' '、 n' +
  61. '' name ':' zhangsan ' n' +
  62. '}'
  63. log( '-------> jsonFromServer:' + jsonStrFromServer)
  64. {を試してください
  65. User2 user2 = gson.fromJson(jsonStrFromServer、User2.class)
  66. ログ( '------> gson解析:' + user2)
  67. } catch(例外e){
  68. ログ( '------> gson解析例外:' + e)
  69. }
  70. {を試してください
  71. ユーザーuser = gson.fromJson(jsonStrFromServer、User.class)
  72. Log( '------> JsonAdapterアノテーションの解析:' +ユーザー)
  73. } catch(JsonParseException e){// java.lang.NumberFormatException:空の文字列
  74. Log( '------> JsonAdapterアノテーション例外:' + e)
  75. }
  76. }
  77. }

演算結果:

[java] プレーンビュー コピー

印刷 コード

  1. -------> jsonFromServer:{
  2. '年齢': ''、
  3. '名前': '張山'
  4. }
  5. ------> gson解析例外:com.google.gson.JsonSyntaxException:java.lang.NumberFormatException:空の文字列
  6. ------> JsonAdapterアノテーション解決策:User {name = 'zhangsan'、age = 0}

[java] プレーンビュー コピー

印刷 コード

  1. サーバーをスキップしてjsonの不合理なピットを返すことに成功したことがわかりますか?

[java] プレーンビュー コピー

印刷 コード

  1. has to vomit, like this server-side error, it should be completely due to the unreasonable return of the server json,

[java] view plain copy

print ?  CODE

  1. Often the boss will find the client reason, how can it collapse? Why didn't you show it? The boss won't care if the data is returned unreasonably!

[java] view plain copy

print ?  CODE

  1. Doing a client needs considerable affordability, agree with the point of praise

[java] view plain copy

print ?  CODE

  1. 実際、上記の保険の方法は非常に安全ですが、維持する場所がたくさんあり、コードの量が多いため、別の方法を紹介します:JsonSerializerとJsonDeserializerの関係の一方的な処理、タイプをグローバルに登録できます処理:例を参照してください:

    パッケージcom.xuan.gson
  2. com.google.gson.Gsonをインポートします
  3. com.google.gson.GsonBuilderをインポートします
  4. インポートcom.google.gson.JsonDeserializationContext
  5. com.google.gson.JsonDeserializerをインポートします
  6. com.google.gson.JsonElementをインポートします
  7. インポートcom.google.gson.JsonParseException
  8. java.lang.reflect.Typeをインポートします
  9. / **
  10. * @author xuanyouwu
  11. * @email root @ xxxxx
  12. * @time 2016-05-18 11:20
  13. * /
  14. パブリッククラスGsonTest10 {
  15. private static void log(String msg){
  16. System.out.println(msg)
  17. }
  18. public static class User {
  19. パブリック文字列名
  20. public int age
  21. @オーバーライド
  22. public String toString(){
  23. 'User {' +を返します
  24. 'name =' '+ name +' '' +
  25. '、年齢=' +年齢+
  26. '}'
  27. }
  28. }
  29. public static void main(String [] args)は例外をスローします{
  30. JsonDeserializer jsonDeserializer = new JsonDeserializer(){
  31. @オーバーライド
  32. public Integer deserialize(JsonElement json、Type typeOfT、JsonDeserializationContext context)はJsonParseException {をスローします
  33. {を試してください
  34. json.getAsInt()を返す
  35. } catch(NumberFormatException e){
  36. 0を返す
  37. }
  38. }
  39. }
  40. Gson gson = new GsonBuilder()
  41. .registerTypeAdapter(int.class、jsonDeserializer)
  42. .create()
  43. 文字列jsonStrFromServer = '{ n' +
  44. ''年齢 ':' '、 n' +
  45. '' name ':' zhangsan ' n' +
  46. '}'
  47. log( '-------> jsonFromServer:' + jsonStrFromServer)
  48. {を試してください
  49. ユーザーuser = gson.fromJson(jsonStrFromServer、User.class)
  50. Log( '------> JsonDeserializerの解析:' +ユーザー)
  51. } catch(例外e){
  52. Log( '------> JsonDeserializer解析例外:' + e)
  53. }
  54. Gson gson1 =新しいGson()
  55. {を試してください
  56. ユーザーuser1 = gson1.fromJson(jsonStrFromServer、User.class)
  57. Log( '------>デフォルトのgson解析:' + user1)
  58. } catch(例外e){
  59. Log( '------>デフォルトのgson解析例外:' + e)
  60. }
  61. }
  62. }

演算結果:

-------> jsonFromServer:{
'年齢': ''、
'名前': '張山'
}
------> JsonDeserializer解決策:User {name = 'zhangsan'、age = 0}
------>デフォルトのgson解析例外:com.google.gson.JsonSyntaxException:java.lang.NumberFormatException:空の文字列

これは、例外の解析を回避するためのグローバルな逆シリアル化ツールを定義します。

保存して、学習に使用してください。そうでない場合は、私を訂正してください。

転載: https://blog.csdn.net/sinat_34093604/article/details/53158059

ブロガー:餌をやる牛