近期使用高德一个接口,上了生产,才发现json里面的list实体,数据格式不一致。有数据的时候,数据为String类型,无数据的时候,数据为“[]”.(如图)
这样的数据格式在使用json转bean的时候,遇到数据格式不一致的,数组类型的会默认填充为“[]”。
我这边的业务需求,对于'[]'那一块数据,全部赋值为null。
可以使用反射进行处理
代码:
实体:
package com.test.gaode;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
public class GaoDeEntity {
private static final long serialVersionUID = -4506875151642772406L;
private String status;
private String info;
private String infocode;
private String count;
private List<GeocodesEntity> geocodes;
}
package com.test.gaode;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
public @Getter
@Setter
class GeocodesEntity {
private static final long serialVersionUID = 942508470576711519L;
private String formattedAddress;
private String country;
private String province;
private String citycode;
private String city;
private String district;
private List<String> township;
private NeighborhoodDomain neighborhood;
private BuildingDomain building;
private String adcode;
private List<String> street;
private List<String> number;
private String location;
private String level;
@Getter
@Setter
class NeighborhoodDomain {
private static final long serialVersionUID = 7216259952414552319L;
private List<String> name;
private List<String> type;
}
@Getter
@Setter
class BuildingDomain {
private static final long serialVersionUID = -4653848900240913579L;
private List<String> name;
private List<String> type;
}
}
package com.test.gaode;
import com.alibaba.fastjson.JSON;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.Collection;
import com.alibaba.fastjson.JSONObject;
import org.reflections.ReflectionUtils;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
public class Test {
@org.junit.Test
public void test2() throws IOException {
String res = FileUtils.readFileToString(new File("C:\\test_data\\data\\test90.txt"), "UTF-8");
GaoDeEntity gaoDeEntity = JSONObject.parseObject(res, GaoDeEntity.class);
GaoDeEntity entity = doentity(gaoDeEntity);
System.out.println("pumaRiskInfo:"+JSON.toJSONString(entity));
}
/**
* 对高德数据进行特殊处理
* 场景:高德返回的数据,如果有值就是String,没有数据就是[]
*/
public static GaoDeEntity doentity(GaoDeEntity gaoDeEntity){
List<GaoDeEntity.GeocodesEntity> geocodes = gaoDeEntity.getGeocodes();
List<GaoDeEntity.GeocodesEntity> geocodesDomainList = geocodes.stream().filter(domain->{
//判断数据的值是否为[]
if (checkFieldAllNull(domain)){
//利用反射 对bean进行赋值为null
byMethod(domain);
return true;
}
return true;
}).collect(Collectors.toList());
gaoDeEntity.setGeocodes(geocodesDomainList);
return gaoDeEntity;
}
/**
* 利用反射 对bean进行赋值为null
* @param t
* @param <T>
* @return
*/
private static <T> T byMethod(T t) {
ReflectionUtils.getAllMethods(t.getClass(), method ->
Objects.requireNonNull(method).getName().indexOf("set") == 0)
.forEach(method -> {
try {
method.invoke(t, new Object[]{null});
} catch (IllegalAccessException | InvocationTargetException e) {
}
});
return t;
}
/**
* 判断数据的值是否为[]
* @param object
* @return
* @throws IllegalAccessException
*/
private static boolean checkFieldAllNull(Object object) {
try {
for (Field f : object.getClass().getDeclaredFields()) {
f.setAccessible(true);
if (Modifier.isFinal(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) {
continue;
}
if (!isEmpty(f.get(object)) ) {
return false;
}
f.setAccessible(false);
}
return true;
} catch (IllegalAccessException e) {
}
return false;
}
private static boolean isEmpty(Object object) throws IllegalAccessException {
if (object == null) {
return true;
}
if (object instanceof String && Objects.equals(object.toString(),"[]")) {
return true;
}
if (object instanceof Collection && ((Collection) object).isEmpty()) {
return true;
}
if (object instanceof Object) {
for (Field f : object.getClass().getDeclaredFields()) {
f.setAccessible(true);
if (Modifier.isFinal(f.getModifiers()) && Modifier.isStatic(f.getModifiers())) {
continue;
}
if (f.get(object) instanceof Collection && ((Collection) f.get(object)).isEmpty()) {
return true;
}
f.setAccessible(false);
return false;
}
return true;
}
return false;
}
}
原始报文:test90.txt
{
"status": "1",
"info": "OK",
"infocode": "10000",
"count": "2",
"geocodes": [
{
"formatted_address": "江苏省南京市溧水区永阳镇",
"country": "中国",
"province": "江苏省",
"citycode": "025",
"city": "南京市",
"district": "溧水区",
"township": [],
"neighborhood": {
"name": ["南京市","南京市","南京市"],
"type": []
},
"building": {
"name": [],
"type": []
},
"adcode": "320117",
"street": [],
"number": [],
"location": "119.044331,31.659977",
"level": "乡镇"
},
{
"formatted_address": [],
"country": [],
"province": [],
"citycode": [],
"city": [],
"district": [],
"township": [],
"neighborhood": {
"name": [],
"type": []
},
"building": {
"name": [],
"type": []
},
"adcode": [],
"street": [],
"number": [],
"location": [],
"level": []
}
]
}
执行结果:数据格式不一致的全部赋值为null
{
"count": "2",
"geocodes": [{
"adcode": "320117",
"building": {
"name": [],
"type": []
},
"city": "南京市",
"citycode": "025",
"country": "中国",
"district": "溧水区",
"formattedAddress": "江苏省南京市溧水区永阳镇",
"level": "乡镇",
"location": "119.044331,31.659977",
"neighborhood": {
"name": ["南京市", "南京市", "南京市"],
"type": []
},
"number": [],
"province": "江苏省",
"street": [],
"township": []
}, {}],
"info": "OK",
"infocode": "10000",
"status": "1"
}