java map 转bean(map和bean转换)
本文目录
- map和bean转换
- java大神求解答
- java 里的bean与bean之间的对比
- json数组转java对象怎么转
- java对象怎么转json数组 跪求啊
- 在android开发中,map可以完全替代bean吗
- java 中怎么合并同类对象的属性
- java,怎么读取HashMap的bean对象值
map和bean转换
package com.test;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.comm***.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.pojo.User;
public class TestMapBeanConvert {
private static Logger LOGGER = LoggerFactory.getLogger(TestMapBeanConvert.class);
// 将map转为bean
public staticT mapToBean(Map《String, Object》 map, Class clz) {
T bean = null;
try {
bean = clz.newInstance();
// 遍历map中的key,若bean中有这个属性(key),将key对应的value赋值给bean对应的属性
BeanUtils.populate(bean, map); // 将map转为bean
} catch (Exception e) {
LOGGER.info("ERROR ------》 " + e.getMessage());
}
return bean;
}
// 将bean转为map
public staticMapbeanToMap(Object bean) {
Map《String, String》 map = null;
try {
map = BeanUtils.describe(bean); // 将bean转为map
} catch (Exception e) {
LOGGER.info("ERROR ------》 " + e.getMessage());
}
return map;
}
public static void main(String args) {
Map《String, Object》 map = new HashMap《String, Object》();
map.put("name", "六月");
map.put("age",6);
System.err.println("-------------------- from map to bean --------------------");
User user = mapToBean(map, User.class);System.err.println(user.toString());
System.err.println("-------------------- from bean to map --------------------");
Map《String, String》 toMap = beanToMap(user);
for(Entry《String, String》 entry:toMap.entrySet()){
System.out.println("key=" +entry.getKey() +" and value="+entry.getValue());
}
}
}
java大神求解答
您好,这样的:
1、ArrayLis中存放的是Object,你直接get出来会当作Object来处理,Object自然没有getChengji()
这些方法。故使用是必须要强制类型转换为XS类型。
如果你想不这样转换,可以用泛型,如:ArrayList《XS》 aa1=new ArrayList《XS》().
2、ArrayList的遍历的作用是访问List中的每个元素,比如你这里肯定是为了输出每个对象的Chengji。
3、没有关系的话,强制类型转换会抛出异常的,转换前的实际类型必须是转换后类型本身或者基类。这里转换前的实际类型就是XS,所以这样转换是安全的。
java 里的bean与bean之间的对比
PO(persistant object) 持久对象
在o/r映射的时候出现的概念,如果没有o/r映射,没有这个概念存在了。通常对应数据模型(数据库),本身还有部分业务逻辑的处理。可以看成是与数据库中的表相映射的java对象。最简单的PO就是对应数据库中某个表中的一条记录,多个记录可以用PO的集合。PO中应该不包含任何对数据库的操作。
VO(value object) 值对象
通常用于业务层之间的数据传递,和PO一样也是仅仅包含数据而已。但应是抽象出的业务对象,可以和表对应,也可以不,这根据业务的需要.
TO(Transfer Object),数据传输对象
在应用程序不同tie(关系)之间传输的对象
BO(business object) 业务对象
从业务模型的角度看,见UML元件领域模型中的领域对象。封装业务逻辑的java对象,通过调用DAO方法,结合PO,VO进行业务操作。
POJO(plain ordinary java object) 简单无规则java对象
纯的传统意义的java对象。就是说在一些Object/Relation Mapping工具中,能够做到维护数据库表记录的persisent object完全是一个符合Java Bean规范的纯Java对象,没有增加别的属性和方法。
DAO(data access object) 数据访问对象
是一个sun的一个标准j2ee设计模式,这个模式中有个接口就是DAO,它负持久层的操作。为业务层提供接口。此对象用于访问数据库。通常和PO结合使用,DAO中包含了各种数据库的操作方法。通过它的方法,结合PO对数据库进行相关的操作。夹在业务逻辑与数据库资源中间。配合VO, 提供数据库的CRUD操作…
O/R Mapper 对象/关系 映射
定义好所有的mapping之后,这个O/R Mapper可以帮我们做很多的工作。通过这些mappings,这个O/R Mapper可以生成所有的关于对象保存,删除,读取的**L语句,不再需要写那么多行的DAL代码了。
json数组转java对象怎么转
首先需要 comm***-beanutils jar包,然后转bean的方法为:
/**
*
* @Title: transMap2Bean
* @param:@param map
* @param:@param obj
* @return:void
* @Description:Map --》 Bean 1: 利用Introspector,PropertyDescriptor实现 Map --》 Bean
* @throws
*/
public static void transMap2Bean(Map《String, Object》 map, Object obj) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (map.containsKey(key)) {
Object value = map.get(key);
// 得到property对应的setter方法
Method setter = property.getWriteMethod();
setter.invoke(obj, value);
}
}
} catch (Exception e) {
System.out.println("transMap2Bean Error " + e);
}
return;
}
java对象怎么转json数组 跪求啊
JSON-lib这个Java类包用于把bean,map和XML转换成JSON并能够把JSON转回成bean和DynaBean。
***隐藏网址***
还要需要的第3方包:
org.apache.comm***(3.2以上版本)
org.apache.oro
net.sf.ezmorph(ezmorph-1.0.4.jar)
nu.xom
1、List
Java代码
boolean{true,false,true};
JSONArray jsonArray1 = JSONArray.fromObject( boolArray );
System.out.println( jsonArray1 );
// prints
List list =newArrayList();
list.add("first");
list.add("second");
JSONArray jsonArray2 = JSONArray.fromObject( list );
System.out.println( jsonArray2 );
// prints
JSONArray jsonArray3 = JSONArray.fromObject("");
System.out.println( jsonArray3 );
// prints
2、Map
Java代码
Map map =newHashMap();
map.put("name","json");
map.put("bool", Boolean.TRUE );
map.put("int",newInteger(1) );
map.put("arr",newString{"a","b"} );
map.put("func","function(i){ return this.arr; }");
JSONObject json = JSONObject.fromObject( map );
System.out.println( json );
//{"func":function(i){ return this.arr,"int":1,"name":"json","bool":true}
3、BEAN
Java代码
/**
* Bean.java
private String name = "json";
private int pojoId = 1;
private char{’a’,’f’};
private String func1 = "function(i){ return this.opti***; }";
private JSONFunction func2 = new JSONFunction(new String;");
*/
JSONObject jsonObject = JSONObject.fromObject(newJsonBean() );
System.out.println( jsonObject );
//{"func1":function(i){ return this.opti***; }}
4、BEANS
Java代码
/**
* private int row ;
private int col ;
private String value ;
*
*/
List list =newArrayList();
JsonBean2 jb1 =newJsonBean2();
jb1.setCol(1);
jb1.setRow(1);
jb1.setValue("xx");
JsonBean2 jb2 =newJsonBean2();
jb2.setCol(2);
jb2.setRow(2);
jb2.setValue("");
list.add(jb1);
list.add(jb2);
JSONArray ja = JSONArray.fromObject(list);
System.out.println( ja.toString() );
//
5、String to bean
Java代码
String json ="{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:}";
JSONObject jsonObject = JSONObject.fromString(json);
Object bean = JSONObject.toBean( jsonObject );
assertEquals( jsonObject.get("name"), PropertyUtils.getProperty( bean,"name") );
assertEquals( jsonObject.get("bool"), PropertyUtils.getProperty( bean,"bool") );
assertEquals( jsonObject.get("int"), PropertyUtils.getProperty( bean,"int") );
assertEquals( jsonObject.get("double"), PropertyUtils.getProperty( bean,"double") );
assertEquals( jsonObject.get("func"), PropertyUtils.getProperty( bean,"func") );
List expected = JSONArray.toList( jsonObject.getJSONArray("array") );
assertEquals( expected, (List) PropertyUtils.getProperty( bean,"array") );
Java代码
String json ="{\"value\":\"xx\",\"row\":1,\"col\":1}";
JSONObject jsonObject = JSONObject.fromString(json);
JsonBean2 bean = (JsonBean2) JSONObject.toBean( jsonObject, JsonBean2.class);
assertEquals( jsonObject.get("col"),newInteger( bean.getCol()) );
assertEquals( jsonObject.get("row"),newInteger( bean.getRow() ) );
assertEquals( jsonObject.get("value"), bean.getValue() );
6 json to xml
1)
JSONObject json = new JSONObject( true );
String xml = XMLSerializer.write( json );
《o class="object" null="true"》
2)
JSONObject json = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");
String xml = XMLSerializer.write( json );
《o class="object"》
《name type="string"》json《/name》
《bool type="boolean"》true《/bool》
《int type="number"》1《/int》
《/o》
《o class="object"》
《name type="string"》json《/name》
《bool type="boolean"》true《/bool》
《int type="number"》1《/int》
《/o》
3)
JSONArray json = JSONArray.fromObject("");
String xml = XMLSerializer.write( json );
《a class="array"》
《e type="number"》1《/e》
《e type="number"》2《/e》
《e type="number"》3《/e》
《/a》
7 、xml to json
《a class="array"》
《e type="function" params="i,j"》
return matrix;
《/e》
《/a》
《a class="array"》
《e type="function" params="i,j"》
return matrix;
《/e》
《/a》
JSONArray json = (JSONArray) XMLSerializer.read( xml );
System.out.println( json );
// prints
在android开发中,map可以完全替代bean吗
map只能存储键值对,或者嵌套使用(感觉略复杂)。
而bean对象却是可以存储一个完整的包含多属性的复杂对象,在界面绘制时一般用list(map《key,value》)来传递对应的值,但是请求回调接收时还是用bean来装载对象的好。
javaBean的话就是有get/set方法,可以对数据进行一些必要的操作,还有javaBean里面可以添加方法.map的话字段你不确定,需要额外的写好那些key是什么东西。
javaBean字段可以添加注释说明,类型也是固定的,那么使用者就知道该放什么数据,而map如果存放了多个类型只能是object类型的,使用还得知道具体类型,还要做相应的类型转换!)
简单的说:我认为map不能完全替代bean,只是在使用中某些场合可以适当选择map使用下。
java 中怎么合并同类对象的属性
package cn.utils;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.comm***.beanutils.BeanUtils;public class ExtendObject {
/**
* 将相同类型的对象的内容向右合并
* @param beanType 返回对象的类型
* @param initObject 包含原始数据的对象
* @param updateObject包含修改后数据的对象
* @return返回两个对象的合并,相同属性的值如果convertedObject中包含,且不为null的话取它的值,否则取returnedObject的值
*/
@SuppressWarnings("unchecked")
public Object extendObject(Object beanType, Object initObject, Object updateObject){
Map map1 = BeanToMap(initObject);
Map map2 = BeanToMap(updateObject);
List list = getMapKeySet(map1);
for(int i=0; i《list.size(); i++){Object map2Value = map2.get(list.get(i));
if(null!=map2Value){
map1.put(list.get(i), map2Value);
}
}
return MapToBean(beanType, map1);
}
/**
* 将map转化为bean
* @param bean 将要转化成为的对象
* @param map 被转化的map对象
*/
@SuppressWarnings("unchecked")
public Object MapToBean(Object bean,Map map){
Object type = null;
Date date = null ;
try {
type = bean.getClass().newInstance();
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
for(PropertyDescriptor p: beanInfo.getPropertyDescriptors()){
String propertyName = p.getName();
Object mapValue = map.get(propertyName);
//去掉键为’class’的键值对
if(null!=mapValue&&!"class".equals(propertyName)){
//判断该字符转是否为日期类型
if(CheckType.isDateType((String)mapValue)){
String dateType = CheckType.getDateType((String)mapValue);
if(dateType.equals("yyyy-MM-dd HH:mm:ss")){
date = new SimpleDateFormat(dateType).parse((String)mapValue);
p.getWriteMethod().invoke(type, new Timestamp(date.getTime()));
}else{
p.getWriteMethod().invoke(type, date);
}
//判断该字符串是否为整型,同时忽略值为数字,但是类型是字符串的Id们
}else if(CheckType.isInt((String) mapValue)&&(!Pattern.matches("/w*Id", propertyName))){
p.getWriteMethod().invoke(type, Integer.getInteger((String)mapValue).intValue());
//默认剩下的类型都是字符串型
}else{
p.getWriteMethod().invoke(type, mapValue);
}
}
}
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return type;
}
/**
* 将bean转化为map
* @param object
* @return
*/
@SuppressWarnings("unchecked")
public Map BeanToMap(Object object){
Map map = null ;
try {
map = BeanUtils.describe(object);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return map;
}
/**
* 获得对应Map的键值
* @param map
* @return
*/
@SuppressWarnings("unchecked")
public List getMapKeySet(Map map){
List list = new ArrayList();
Iterator iterator = map.keySet().iterator();
while(iterator.hasNext()){
list.add(iterator.next());
}
return list;
}///**
// * @param args
// */
//public static void main(String args) throws Exception{
//System.out.println(isInt("1"));
//Admin a = new Admin();
//a.setAdminId("1");
//a.setAdminPassword("1");
//
//Admin b = new Admin();
//b.setAdminPassword("2");
//Admin c = (Admin)extendObject(new Admin(),a,b);
//System.out.println(c.getAdminId()+"----"+c.getAdminPassword());
//}
}
------------------------------------------------------------------------------------
package cn.utils;
import java.util.regex.Pattern;
public class CheckType {
/**
* 判断该字符串是否为日期类型
* @param str
* @return
*/
public static boolean isDateType(String str){
Boolean b = false;
String dateType1 ="/d{4}-/d{2}-/d{2}/s/d{2}:/d{2}:/d{2}./d*";
String dateType2 ="/d{4}-/d{2}-/d{2}/s/d{2}:/d{2}:/d{2}";
String dateType3 ="/d{4}-/d{2}-/d{2}";
if(Pattern.matches(dateType1, str)||
Pattern.matches(dateType2, str)||
Pattern.matches(dateType3, str)){
b = true;
}
return b;
}/**
* 返回字符串所属日期格式
* @param str
* @return
*/
public static String getDateType(String str){
String dateType1 ="/d{4}-/d{2}-/d{2}/s/d{2}:/d{2}:/d{2}./d*";
String dateType2 ="/d{4}-/d{2}-/d{2}/s/d{2}:/d{2}:/d{2}";
String dateType3 ="/d{4}-/d{2}-/d{2}";
if(Pattern.matches(dateType1, str)||
Pattern.matches(dateType2, str)){
return"yyyy-MM-dd HH:mm:ss";
}
if(Pattern.matches(dateType3, str)){
return"yyyy-MM-dd";
}
return null;
}
/**
* 判断该字符串是否为整型
* @param str
* @return
*/
public static boolean isInt(String str){
Boolean b = false;
if(Pattern.matches("/d+", str)){
b = true;
}
return b;
}
}
java,怎么读取HashMap的bean对象值
你是要根据key拿出bean的吧,那就根据key拿出来呗
cacheMap.get("abc");
cacheMap.get("aaa");
cacheMap.get("bbb");
如果要一次性拿出来
Collection valueCollection = cachemap.values()
更多文章:
java购物车源代码(用J**A+SERVLET+J**ABEAN写购物车代码)
2026年4月19日 09:40
filter函数在哪个版本(我的wps里为什么没有Filter函数)
2026年4月19日 09:20
struts的配置文件是什么(Struts2中如何配置struts、xml)
2026年4月19日 09:00
regression line(linear probability model probit 和 tobit的区别)
2026年4月19日 08:40
ajax请求数据失败(我用Ajax请求数据,但是老不成功提示如下图:然后下面是代码)
2026年4月19日 08:20
二进制编码转换器工具(求十进制数和float二进制码互相转换的软件或者excel函数)
2026年4月19日 07:40
threadripper怎么读(目前**的电脑配置是怎样的)
2026年4月19日 07:00
shadow puppet(我们中国的传统文化有许多就好像剪纸 英文怎么写)
2026年4月19日 06:40




