java使用反射生成geojson字符串
前言
之前在网上看过很多的geojson的方法,都很繁琐,而且每次生成一种geojson的时候,都必须重新书写一个新方法,拼接一种新的geojson字符串返回给前端。但是这从代码的耦合性角度来说却是十分的不合理
实现方式
通过反射获取类的属性,匹配到需要进行拼接字符串的类,获取集合中的每个实体的对应属性值进行自动拼接geojson字符串的方法 具体代码实现方式如下:
public class ToGeojsonUtils {
//private Logger logger = LoggerFactory.getLogger(getClass());
/**
* 将存储实体类的集合,转化成geojson字符串
* @param obj 需要转化成实体类的集合
* @param entity 实体类的class文件
* @param fieleName 属性名字
* @param fieldType 属性类型
* @param geometry geometry类型
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String objectToGeojsonString(List obj,
Class entity,
String fieleName,
String fieldType, String geometry){
List<String> fieldname= RequestParameterUtils.getInstance().splitString(fieleName);
List<String> fieldtype=RequestParameterUtils.getInstance().splitString(fieldType);
if(obj==null){
return "[]";
}else if(obj.size()==0){
return "[]";
}else{
String result = null;
//处理拼接在geojson中的属性名字以及类型
if(fieldname.size()==fieldtype.size()){
}else{
//logger.info("属性名字以及类型格式不对!");
return "";
}
try {
Class clazz=entity;
String geojsonContent="";
List<Method> fieldGetMethods=new ArrayList<Method>();
StringBuilder content=new StringBuilder();
for(int i=0;i<fieldname.size();i++){
if(i==0) {
content.append("geometry");
content.append(":");
content.append(geometry);
content.append(",");
}else {
content.append(fieldname.get(i));
content.append(":");
content.append(fieldtype.get(i));
content.append(",");
}
String name=fieldname.get(i);
String methodname="get"+name.substring(0, 1).toUpperCase() + name.substring(1);
Method method=clazz.getMethod(methodname);
fieldGetMethods.add(method);
}
geojsonContent=content.toString();
SimpleFeatureType TYPE = DataUtilities.createType("Link",geojsonContent);
FeatureJSON fjson = new FeatureJSON(new GeometryJSON(13));
DefaultFeatureCollection featureCollection = new DefaultFeatureCollection();
for (int i=0 ; i<obj.size() ; i++) {
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(TYPE);
for(Method method:fieldGetMethods){
featureBuilder.add(method.invoke(obj.get(i)));
}
SimpleFeature feature = featureBuilder.buildFeature(null);
featureCollection.add(feature);
}
StringWriter writer = new StringWriter();
fjson.writeFeatureCollection(featureCollection, writer);
result=writer.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
}
