Object转成map对象
程序员文章站
2022-06-15 09:56:40
...
1、Object转换成map的方法
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* 将Object对象里面的属性和值转化成Map对象
*
* @param obj
* @return
* @throws IllegalAccessException
*/
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<String,Object>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
map.put(fieldName, value);
}
return map;
}
2、转换前的数据格式
SearchHit{id='awQWpXgBwGXBeoctg1F5', score=2.1747518, sortValues=[], content=User(id=awQWpXgBwGXBeoctg1F5, name=吴京, msg=我是演员, job=演员, sex=男, age=12, createDate=Tue Apr 06 08:00:00 CST 2021), highlightFields={}}
3、转换后的数据
{score=2.1747518, innerHits={}, highlightFields={}, index=user, id=awQWpXgBwGXBeoctg1F5, nestedMetaData=null, sortValues=[], content=User(id=awQWpXgBwGXBeoctg1F5, name=吴京, msg=我是演员, job=演员, sex=男, age=12, createDate=Tue Apr 06 08:00:00 CST 2021)}
4、取map中的值
map.get("content")
5、map转实体对象
List searchHits = user.getSearchHits();
List<User> users = new ArrayList<>();
for (Object o : searchHits) {
Map<String, Object> map = new HashMap<>();
map = objectToMap(o);
Map<String, Object> userMap = objectToMap(map.get("content"));
User user1 = mapToBean(userMap);
System.out.println("哈哈哈哈哈转换成功:"+user1.getMsg());
users.add(user1);
}
6、map转实体类对象利用的方法
参数类型按实际的实体类进行增加
/**
* map 转 实体类
*
* @param map
* @return
* @throws Exception
*/
public User mapToBean(Map<String, Object> map)
throws Exception {
User permission = new User();
if (map != null) {
Field[] declaredFields = User.class.getDeclaredFields();
if (declaredFields != null) {
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
Set<String> mapKeys = map.keySet();
for (String mapKey : mapKeys) {
if (declaredField.getType().toString().contains("Integer"))//判断属性类型 进行转换,map中存放的是Object对象需要转换 实体类中有多少类型就加多少类型,实体类属性用包装类;
if (declaredField.getName().equals(mapKey)) {
declaredField.set(permission, Integer.valueOf(map.get(mapKey).toString()));
break;
}
if (declaredField.getType().toString().contains("String"))//判断属性类型 进行转换;
if (declaredField.getName().equals(mapKey)) {
declaredField.set(permission, map.get(mapKey));
break;
}
if (declaredField.getType().toString().contains("Float"))//判断属性类型 进行转换;
if (declaredField.getName().equals(mapKey)) {
declaredField.set(permission, Float.valueOf(map.get(mapKey).toString()));
break;
}
if (declaredField.getType().toString().contains("Long"))//判断属性类型 进行转换;
if (declaredField.getName().equals(mapKey)) {
declaredField.set(permission, Long.valueOf(map.get(mapKey).toString()));
break;
}
if (declaredField.getType().toString().contains("Date"))//判断属性类型 进行转换;
if (declaredField.getName().equals(mapKey)) {
String s = map.get(mapKey).toString();
Date parse = parse(s, "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
declaredField.set(permission, parse);
break;
}
}
}
}
}
return permission;
7、里面用到的时间格式是格林威治,实体类存的是Date,具体方法如下:
// 格林威治时间转Date
private Date parse(String str, String pattern, Locale locale) {
if (str == null || pattern == null) {
return null;
}
try {
return new SimpleDateFormat(pattern, locale).parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
8、完整代码在下面,因为我用的是springboot+es,所以,根据具体情况灵活变动
package com.springboot.demo.es;
import com.springboot.demo.entity.User;
import com.springboot.demo.mapper.UserResipotry;
import org.apache.tomcat.util.buf.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import javax.xml.crypto.Data;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* @author dt
* @date 2021年04月06日10:47
*/
@SpringBootTest
public class EsDemo01 {
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
@Test
void test4() throws Exception {
//组合条件对象
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
boolQuery.must(QueryBuilders.matchQuery("name", "吴京"));
NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
nativeSearchQueryBuilder.withQuery(boolQuery);
SearchHits user = elasticsearchRestTemplate.search(nativeSearchQueryBuilder.build(), User.class, IndexCoordinates.of("user"));
List searchHits = user.getSearchHits();
List<User> users = new ArrayList<>();
for (Object o : searchHits) {
Map<String, Object> map = new HashMap<>();
map = objectToMap(o);
Map<String, Object> userMap = objectToMap(map.get("content"));
User user1 = mapToBean(userMap);
System.out.println("哈哈哈哈哈转换成功:"+user1.getMsg());
users.add(user1);
}
System.out.println(users);
}
/**
* 将Object对象里面的属性和值转化成Map对象
*
* @param obj
* @return
* @throws IllegalAccessException
*/
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<String, Object>();
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
map.put(fieldName, value);
}
return map;
}
/**
* map 转 实体类
*
* @param map
* @return
* @throws Exception
*/
public User mapToBean(Map<String, Object> map)
throws Exception {
User permission = new User();
if (map != null) {
Field[] declaredFields = User.class.getDeclaredFields();
if (declaredFields != null) {
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
Set<String> mapKeys = map.keySet();
for (String mapKey : mapKeys) {
if (declaredField.getType().toString().contains("Integer"))//判断属性类型 进行转换,map中存放的是Object对象需要转换 实体类中有多少类型就加多少类型,实体类属性用包装类;
if (declaredField.getName().equals(mapKey)) {
declaredField.set(permission, Integer.valueOf(map.get(mapKey).toString()));
break;
}
if (declaredField.getType().toString().contains("String"))//判断属性类型 进行转换;
if (declaredField.getName().equals(mapKey)) {
declaredField.set(permission, map.get(mapKey));
break;
}
if (declaredField.getType().toString().contains("Float"))//判断属性类型 进行转换;
if (declaredField.getName().equals(mapKey)) {
declaredField.set(permission, Float.valueOf(map.get(mapKey).toString()));
break;
}
if (declaredField.getType().toString().contains("Long"))//判断属性类型 进行转换;
if (declaredField.getName().equals(mapKey)) {
declaredField.set(permission, Long.valueOf(map.get(mapKey).toString()));
break;
}
if (declaredField.getType().toString().contains("Date"))//判断属性类型 进行转换;
if (declaredField.getName().equals(mapKey)) {
String s = map.get(mapKey).toString();
Date parse = parse(s, "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
declaredField.set(permission, parse);
break;
}
}
}
}
}
return permission;
}
@Test
public void getTime() throws ParseException {
String str = "Tue Apr 06 08:00:00 CST 2021";
Date date = parse(str, "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
}
// 格林威治时间转Date
private Date parse(String str, String pattern, Locale locale) {
if (str == null || pattern == null) {
return null;
}
try {
return new SimpleDateFormat(pattern, locale).parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
9、那些转换方法都可以单独用
参考文章链接:
https://blog.csdn.net/qq_15204179/article/details/86677123
上一篇: 五花肉菜名,五花肉的菜名有些什么
下一篇: 九种最神奇的快速减肥偏方