Skip to content

Commit

Permalink
* 修改gson 解析未知对象的时候会多双引号的bug
Browse files Browse the repository at this point in the history
  • Loading branch information
eajon authored and wengyijiong committed Jan 23, 2019
1 parent b9c4a14 commit 3b6055f
Show file tree
Hide file tree
Showing 7 changed files with 256 additions and 36 deletions.
18 changes: 18 additions & 0 deletions RxHttp/src/main/java/com/github/eajon/annotation/Name.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.github.eajon.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


/**
* Created by threshold on 2017/1/16.
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Name {
String value();

boolean require() default true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ public static ApiException handleException(Throwable e) {
|| e instanceof JsonSyntaxException
|| e instanceof JsonSerializer
|| e instanceof NotSerializableException
|| e instanceof ParseException) {
|| e instanceof ParseException
|| e instanceof UnsupportedOperationException) {
ex = new ApiException(e, ERROR.PARSE_ERROR);
ex.bodyMessage = "解析错误";
return ex;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
*
* @author wengyijiong
*/
public class HttpResponseFunction<T> implements Function <JsonElement, Object> {
public class HttpResponseFunction<T> implements Function<JsonElement, Object> {


private Type type;
Expand All @@ -29,7 +29,11 @@ public Object apply(@NonNull JsonElement response) throws Exception {
LoggerUtils.json(response.toString());
/*此处不再处理业务相关逻辑交由开发者重写httpCallback*/
if (type == null) {
return new Gson().toJson(response);
if (response.isJsonObject()) {
return response.toString();
} else {
return response.getAsString();
}
}
return new Gson().fromJson(response, type);

Expand Down
66 changes: 47 additions & 19 deletions RxHttp/src/main/java/com/github/eajon/util/GsonUtils.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.github.eajon.util;

import android.text.TextUtils;

import com.github.eajon.annotation.Name;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
Expand All @@ -9,37 +12,62 @@
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class GsonUtils {

private static Gson gson = new GsonBuilder()
.registerTypeAdapter(
new TypeToken<Map<String, Object>>() {
}.getType(),
new JsonDeserializer<Map<String, Object>>() {
@Override
public Map<String, Object> deserialize(
JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Map<String, Object> map = new HashMap<>();
JsonObject jsonObject = json.getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
for (Map.Entry<String, JsonElement> entry : entrySet) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
}).create();
public static Gson buildGson(Object object) {
return new GsonBuilder()
.registerTypeAdapter(
new TypeToken<Map<String, String>>() {
}.getType(),
new MapJsonDeserializer(object)).create();
}

public static Map<String, Object> objectToMap(Object object) {
Map<String, Object> map = gson.fromJson(gson.toJson(object), new TypeToken<Map<String, Object>>() {
Gson gson = buildGson(object);
Map<String, Object> map = gson.fromJson(gson.toJson(object), new TypeToken<Map<String, String>>() {
}.getType());
return map;
}

private static class MapJsonDeserializer implements JsonDeserializer<Map<String, Object>> {

private Object object;

private MapJsonDeserializer(Object object) {
this.object = object;
}

@Override
public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Map<String, Object> map = new HashMap<>();
JsonObject jsonObject = json.getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
Class clazz = object.getClass();
for (Map.Entry<String, JsonElement> entry : entrySet) {
try {
Field field = clazz.getDeclaredField(entry.getKey());
boolean hasName = field.isAnnotationPresent(Name.class);
if (hasName) {
Name name = field.getAnnotation(Name.class);
if (name.require()) {
map.put(TextUtils.isEmpty(name.value()) ? entry.getKey() : name.value(), entry.getValue().isJsonObject() ? entry.getValue().toString() : entry.getValue().getAsString());
}
} else {
map.put(entry.getKey(), entry.getValue().isJsonObject() ? entry.getValue().toString() : entry.getValue().getAsString());
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
return map;
}
}
}


17 changes: 11 additions & 6 deletions app/src/main/java/com/eajon/my/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import com.eajon.my.base.BaseActivity;
import com.eajon.my.model.BaseResponse;
import com.eajon.my.model.CommonResponse;
import com.eajon.my.model.Profile;
import com.eajon.my.model.Weather;
import com.eajon.my.util.PhotoUtils;
import com.eajon.my.util.ZhihuImagePicker;
Expand All @@ -30,6 +31,7 @@
import com.github.eajon.task.UploadTask;
import com.github.eajon.util.LoggerUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qingmei2.rximagepicker.core.RxImagePicker;
import com.qingmei2.rximagepicker.entity.Result;
import com.qingmei2.rximagepicker_extension.MimeType;
Expand All @@ -42,6 +44,7 @@
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -87,15 +90,15 @@ protected int setContentId() {

@Override
protected void initView() {
//官方MVVM
// 官方MVVM
WeatherModule weatherModule = ViewModelProviders.of(this).get(WeatherModule.class);
weatherModule.getWeather().observe(this, new android.arch.lifecycle.Observer<Weather>() {
@Override
public void onChanged(@Nullable Weather weather) {
content.setText(new Gson().toJson(weather));
}
});
//RxHttp MVVM
// RxHttp MVVM
WeatherModule2 weatherModule2 = ViewModelProviders.of(this).get(WeatherModule2.class);
weatherModule2.getWeather();

Expand Down Expand Up @@ -172,12 +175,14 @@ private void doProfile() {
new RxHttp.Builder()
.get()
.apiUrl("api/user/profile")
.entity(CommonResponse.class)
.build()
.request(new HttpObserver<CommonResponse>() {
.request(new HttpObserver<String>() {
@Override
public void onSuccess(CommonResponse o) {
content.setText(o.getData().toString());
public void onSuccess(String o) {
Type type = new TypeToken<CommonResponse<Profile>>() {
}.getType();
CommonResponse<Profile> profile = new Gson().fromJson(o, type);
content.setText(profile.getData().getNickname());
}

@Override
Expand Down
87 changes: 87 additions & 0 deletions app/src/main/java/com/eajon/my/model/Profile.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package com.eajon.my.model;

public class Profile {

private String city;
private String country;
private String headImgUrl;
private int id;
private String language;
private String mobile;
private String name;
private String nickname;
private int sex;

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

public String getHeadImgUrl() {
return headImgUrl;
}

public void setHeadImgUrl(String headImgUrl) {
this.headImgUrl = headImgUrl;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getLanguage() {
return language;
}

public void setLanguage(String language) {
this.language = language;
}

public String getMobile() {
return mobile;
}

public void setMobile(String mobile) {
this.mobile = mobile;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getNickname() {
return nickname;
}

public void setNickname(String nickname) {
this.nickname = nickname;
}

public int getSex() {
return sex;
}

public void setSex(int sex) {
this.sex = sex;
}
}

Loading

0 comments on commit 3b6055f

Please sign in to comment.