Skip to content

Commit 2a20aaf

Browse files
committed
优化框架代码写法
适配 Gson 2.10.1 版本
1 parent f130068 commit 2a20aaf

File tree

9 files changed

+88
-35
lines changed

9 files changed

+88
-35
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,9 @@ android {
3939
4040
dependencies {
4141
// Gson 解析容错:https://github.com/getActivity/GsonFactory
42-
implementation 'com.github.getActivity:GsonFactory:6.3'
42+
implementation 'com.github.getActivity:GsonFactory:6.5'
4343
// Json 解析框架:https://github.com/google/gson
44-
implementation 'com.google.code.gson:gson:2.9.1'
44+
implementation 'com.google.code.gson:gson:2.10.1'
4545
}
4646
```
4747

@@ -262,6 +262,8 @@ GsonFactory.setJsonCallback(new JsonCallback() {
262262

263263
* 省市区 Json 数据:[ProvinceJson](https://github.com/getActivity/ProvinceJson) ![](https://img.shields.io/github/stars/getActivity/ProvinceJson.svg) ![](https://img.shields.io/github/forks/getActivity/ProvinceJson.svg)
264264

265+
* Markdown 语法文档:[MarkdownDoc](https://github.com/getActivity/MarkdownDoc) ![](https://img.shields.io/github/stars/getActivity/MarkdownDoc.svg) ![](https://img.shields.io/github/forks/getActivity/MarkdownDoc.svg)
266+
265267
#### 微信公众号:Android轮子哥
266268

267269
![](https://raw.githubusercontent.com/getActivity/Donate/master/picture/official_ccount.png)

app/build.gradle

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@ android {
55

66
defaultConfig {
77
applicationId "com.hjq.gson.factory.demo"
8-
minSdkVersion 14
8+
minSdkVersion 16
99
targetSdkVersion 31
10-
versionCode 63
11-
versionName "6.3"
10+
versionCode 65
11+
versionName "6.5"
1212
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
1313
}
1414

@@ -67,7 +67,10 @@ dependencies {
6767

6868
// Json 解析框架:https://github.com/google/gson
6969
// noinspection GradleDependency
70-
implementation 'com.google.code.gson:gson:2.9.1'
70+
implementation 'com.google.code.gson:gson:2.10.1'
71+
72+
// 标题栏框架:https://github.com/getActivity/TitleBar
73+
implementation 'com.github.getActivity:TitleBar:10.0'
7174

7275
// Bugly 异常捕捉:https://bugly.qq.com/docs/user-guide/instruction-manual-android/?v=20190418140644
7376
implementation 'com.tencent.bugly:crashreport:4.0.4'

app/src/androidTest/java/com/hjq/gson/factory/test/JsonUnitTest.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.hjq.gson.factory.test;
22

33
import android.content.Context;
4+
import android.util.Log;
45

56
import androidx.test.platform.app.InstrumentationRegistry;
67

@@ -9,7 +10,6 @@
910
import com.google.gson.stream.JsonToken;
1011
import com.hjq.gson.factory.GsonFactory;
1112
import com.hjq.gson.factory.JsonCallback;
12-
import com.tencent.bugly.crashreport.CrashReport;
1313

1414
import org.junit.After;
1515
import org.junit.Before;
@@ -35,15 +35,16 @@ public final class JsonUnitTest {
3535
*/
3636
@Before
3737
public void onTestBefore() {
38+
// CrashReport.initCrashReport(InstrumentationRegistry.getInstrumentation().getContext());
3839
mGson = GsonFactory.getSingletonGson();
3940
// 设置 Json 解析容错监听
4041
GsonFactory.setJsonCallback(new JsonCallback() {
4142

4243
@Override
4344
public void onTypeException(TypeToken<?> typeToken, String fieldName, JsonToken jsonToken) {
44-
// Log.e("GsonFactory", "类型解析异常:" + typeToken + "#" + fieldName + ",后台返回的类型为:" + jsonToken);
45+
Log.e("GsonFactory", "类型解析异常:" + typeToken + "#" + fieldName + ",后台返回的类型为:" + jsonToken);
4546
// 上报到 Bugly 错误列表
46-
CrashReport.postCatchedException(new IllegalArgumentException("类型解析异常:" + typeToken + "#" + fieldName + ",后台返回的类型为:" + jsonToken));
47+
// CrashReport.postCatchedException(new IllegalArgumentException("类型解析异常:" + typeToken + "#" + fieldName + ",后台返回的类型为:" + jsonToken));
4748
}
4849
});
4950
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,29 @@
11
package com.hjq.gson.factory.demo;
22

3+
import android.content.Intent;
4+
import android.net.Uri;
35
import android.os.Bundle;
46

57
import androidx.appcompat.app.AppCompatActivity;
68

9+
import com.hjq.bar.OnTitleBarListener;
10+
import com.hjq.bar.TitleBar;
11+
712
public class MainActivity extends AppCompatActivity {
813

914
@Override
1015
protected void onCreate(Bundle savedInstanceState) {
1116
super.onCreate(savedInstanceState);
1217
setContentView(R.layout.activity_main);
18+
19+
TitleBar titleBar = findViewById(R.id.tb_main_bar);
20+
titleBar.setOnTitleBarListener(new OnTitleBarListener() {
21+
@Override
22+
public void onTitleClick(TitleBar titleBar) {
23+
Intent intent = new Intent(Intent.ACTION_VIEW);
24+
intent.setData(Uri.parse(titleBar.getTitle().toString()));
25+
startActivity(intent);
26+
}
27+
});
1328
}
1429
}
Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<?xml version="1.0" encoding="utf-8"?>
2-
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
2+
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
33
xmlns:app="http://schemas.android.com/apk/res-auto"
44
xmlns:tools="http://schemas.android.com/tools"
55
android:layout_width="match_parent"
@@ -8,12 +8,19 @@
88
android:orientation="vertical"
99
tools:context=".MainActivity">
1010

11-
<TextView
12-
android:layout_width="wrap_content"
11+
<com.hjq.bar.TitleBar
12+
android:id="@+id/tb_main_bar"
13+
android:layout_width="match_parent"
1314
android:layout_height="wrap_content"
14-
android:layout_gravity="center"
15+
app:leftIcon="@null"
16+
app:title="https://github.com/getActivity/GsonFactory" />
17+
18+
<TextView
19+
android:layout_width="match_parent"
20+
android:layout_height="match_parent"
21+
android:gravity="center"
1522
android:text="请看单元测试的代码"
1623
android:textColor="#333333"
1724
android:textSize="18sp" />
1825

19-
</FrameLayout>
26+
</LinearLayout>

library/build.gradle

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ android {
55

66
defaultConfig {
77
minSdkVersion 11
8-
versionCode 63
9-
versionName "6.3"
8+
versionCode 65
9+
versionName "6.5"
1010
}
1111

1212
// 使用 JDK 1.8
@@ -34,7 +34,7 @@ afterEvaluate {
3434
dependencies {
3535
// Json 解析框架:https://github.com/google/gson
3636
// noinspection GradleDependency
37-
implementation 'com.google.code.gson:gson:2.9.1'
37+
implementation 'com.google.code.gson:gson:2.10.1'
3838
}
3939

4040
// 防止编码问题

library/src/main/java/com/hjq/gson/factory/element/ReflectiveTypeAdapterFactory.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,6 @@ private static boolean excludeField(Field field, boolean serialize, Excluder exc
130130
}
131131

132132
private List<String> getFieldNames(Field field) {
133-
return ReflectiveTypeUtils.getFieldName(mFieldNamingPolicy, field);
133+
return ReflectiveTypeUtils.getFieldNames(mFieldNamingPolicy, field);
134134
}
135135
}

library/src/main/java/com/hjq/gson/factory/element/ReflectiveTypeUtils.java

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@
2424
import java.util.ArrayList;
2525
import java.util.BitSet;
2626
import java.util.Calendar;
27+
import java.util.Collections;
2728
import java.util.Currency;
2829
import java.util.Date;
2930
import java.util.GregorianCalendar;
30-
import java.util.LinkedList;
3131
import java.util.List;
3232
import java.util.Locale;
3333
import java.util.UUID;
@@ -174,18 +174,22 @@ public static TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructor,
174174
return typeAdapter;
175175
}
176176

177-
public static List<String> getFieldName(FieldNamingStrategy fieldNamingPolicy, Field field) {
178-
SerializedName serializedName = field.getAnnotation(SerializedName.class);
179-
List<String> fieldNames = new LinkedList<>();
180-
if (serializedName == null) {
181-
fieldNames.add(fieldNamingPolicy.translateName(field));
182-
} else {
183-
fieldNames.add(serializedName.value());
184-
String[] alternates = serializedName.alternate();
185-
for (String alternate : alternates) {
186-
fieldNames.add(alternate);
187-
}
177+
public static List<String> getFieldNames(FieldNamingStrategy fieldNamingPolicy, Field field) {
178+
SerializedName annotation = field.getAnnotation(SerializedName.class);
179+
if (annotation == null) {
180+
String name = fieldNamingPolicy.translateName(field);
181+
return Collections.singletonList(name);
188182
}
183+
184+
String serializedName = annotation.value();
185+
String[] alternates = annotation.alternate();
186+
if (alternates.length == 0) {
187+
return Collections.singletonList(serializedName);
188+
}
189+
190+
List<String> fieldNames = new ArrayList<>(alternates.length + 1);
191+
fieldNames.add(serializedName);
192+
Collections.addAll(fieldNames, alternates);
189193
return fieldNames;
190194
}
191195
}

library/src/main/java/com/hjq/gson/factory/element/TypeAdapterRuntimeTypeWrapper.java

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import com.google.gson.Gson;
44
import com.google.gson.TypeAdapter;
55
import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory;
6+
import com.google.gson.internal.bind.SerializationDelegatingTypeAdapter;
67
import com.google.gson.reflect.TypeToken;
78
import com.google.gson.stream.JsonReader;
89
import com.google.gson.stream.JsonWriter;
@@ -43,31 +44,51 @@ public void write(JsonWriter out, T value) throws IOException {
4344
// Third preference: reflective type adapter for the runtime type (if it is a sub class of the declared type)
4445
// Fourth preference: reflective type adapter for the declared type
4546

46-
TypeAdapter chosen = mDelegate;
47+
TypeAdapter chosen;
4748
Type runtimeType = getRuntimeTypeIfMoreSpecific(mType, value);
4849
if (runtimeType != mType) {
4950
TypeAdapter runtimeTypeAdapter = mGson.getAdapter(TypeToken.get(runtimeType));
5051
if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) {
5152
// The user registered a type adapter for the runtime type, so we will use that
5253
chosen = runtimeTypeAdapter;
53-
} else if (!(mDelegate instanceof ReflectiveTypeAdapterFactory.Adapter)) {
54+
} else if (!isReflective(mDelegate)) {
5455
// The user registered a type adapter for Base class, so we prefer it over the
5556
// reflective type adapter for the runtime type
5657
chosen = mDelegate;
5758
} else {
5859
// Use the type adapter for runtime type
5960
chosen = runtimeTypeAdapter;
6061
}
62+
} else {
63+
chosen = mDelegate;
6164
}
6265
chosen.write(out, value);
6366
}
6467

68+
/**
69+
* Returns whether the type adapter uses reflection.
70+
*
71+
* @param typeAdapter the type adapter to check.
72+
*/
73+
private static boolean isReflective(TypeAdapter<?> typeAdapter) {
74+
// Run this in loop in case multiple delegating adapters are nested
75+
while (typeAdapter instanceof SerializationDelegatingTypeAdapter) {
76+
TypeAdapter<?> delegate = ((SerializationDelegatingTypeAdapter<?>) typeAdapter).getSerializationDelegate();
77+
// Break if adapter does not delegate serialization
78+
if (delegate == typeAdapter) {
79+
break;
80+
}
81+
typeAdapter = delegate;
82+
}
83+
84+
return typeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter;
85+
}
86+
6587
/**
6688
* Finds a compatible runtime type if it is more specific
6789
*/
68-
private Type getRuntimeTypeIfMoreSpecific(Type type, Object value) {
69-
if (value != null
70-
&& (type == Object.class || type instanceof TypeVariable<?> || type instanceof Class<?>)) {
90+
private static Type getRuntimeTypeIfMoreSpecific(Type type, Object value) {
91+
if (value != null && (type instanceof Class<?> || type instanceof TypeVariable<?>)) {
7192
type = value.getClass();
7293
}
7394
return type;

0 commit comments

Comments
 (0)