找不到类objectmapper(我在action中的某一个add方法有个属性值,属于局部变量而不是action变量,通过返回结果类)

本文目录
- 我在action中的某一个add方法有个属性值,属于局部变量而不是action变量,通过返回结果类
- 有没有将json直接转换生成Java类的工具软件
- org.codehaus.jackson.map.objectmapper在哪个jar包
- 令狐工具配置方式有什么几种类型
- java实体类怎么转换成json
- java如何返回json格式
- jackson怎么将list转为json字符串
我在action中的某一个add方法有个属性值,属于局部变量而不是action变量,通过返回结果类
直接肯定是拿不到的,毕竟是局部变量嘛,但是通过特殊的手段是可以的,如:
public String add() throws Exception {
String username = "zangsan";
Map《String, Object》 map = new HashMap《String, Object》 ();
map.put("username", username);
jsonOut(map);
}
/**
* 向浏览器响应json字符串
* @param jsonMap
* @return
* @throws Exception
*/
public String jsonOut(Object jsonMap)throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(jsonMap);
response.setContentType("text/json;charset=UTF-8");
response.getWriter().print(jsonString);
return null;
}
在js中就可以通过jsonObject.属性名拿到了。
有没有将json直接转换生成Java类的工具软件
使用Jackson可以将json转为Java对象,同样也可以将java对象转为json字符串,并且Spring框架内部也是使用的此jar。
实例:将json转为java对象
/*
下面的id,name,age同是User实体类的属性
*/
// 将json转为Java对象
String json = "{\"id\":1,\"name\":\"张三\",\"age\":18}";
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);、
// 将json转为Java数组对象
String json = "";
ObjectMapper mapper = new ObjectMapper();
User.class);
org.codehaus.jackson.map.objectmapper在哪个jar包
生成不了bean对象,应该是找不到相应包 。查看是否包可以共享,看是否有相同类名,并在相同包下面。 json-lib-2.3和jackson-core-asl1.9.1 如果通过json做ajax传递数据,建议使用 json-lib-2.3
令狐工具配置方式有什么几种类型
spring data redis 序列化有jdk 、jackson、string 等几种类型,自带的jackson不熟悉怎么使用,于是用string类型序列化,把对象先用工具类转成string,代码如下:
application.xml中配置
复制代码
《bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 》
《property name="hostName" value="${redis.hostName}"》《/property》
《property name="port" value="${redis.port}"》《/property》
《property name="password" value="${redis.password}"》《/property》
《property name="timeout" value="${redis.timeout}" /》
《property name="usePool" value="true" /》
《property name="poolConfig" ref="jedisPoolConfig" /》
《/bean》
《bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"》
《property name="maxTotal" value="${redis.maxTotal}"》《/property》
《property name="maxIdle" value="${redis.maxIdle}"》《/property》
《property name="maxWaitMillis" value="${redis.maxWaitMillis}"》《/property》
《property name="testOnBorrow" value="${redis.testOnBorrow}"》《/property》
《/bean》
《bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /》
《!-- 《bean id="jacksonJsonRedisSerializer" class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer" 》
《constructor-arg type="java.lang.Class" value="java.lang.Object"/》
《/bean》 --》
《bean id="jacksonJsonRedisSerializer" class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer" 》
《constructor-arg type="java.lang.Class" value="java.lang.Object"/》
《/bean》
《bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/》
《bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"》
《property name="connectionFactory" ref="jedisConnectionFactory"》《/property》
《property name="keySerializer" ref="stringRedisSerializer"/》
《property name="valueSerializer" ref="stringRedisSerializer" /》
《property name="hashKeySerializer" ref="stringRedisSerializer" /》
《property name="hashValueSerializer" ref="stringRedisSerializer"/》
《/bean》
复制代码
复制代码
《bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"》
《property name="locations"》
《list》
《value》classpath:jdbc.properties《/value》
《value》classpath:redis.properties《/value》
《/list》
《/property》
《/bean》
redis.properties
#redis连接池配置
redis.maxTotal=300
redis.maxIdle=20
#读取超时
redis.maxWaitMillis=5000
redis.testOnBorrow=true
#redis连接配置
redis.hostName=192.168.100.75
redis.port=6379
redis.password=desc@1997
#连接超时
redis.timeout=5000
复制代码
RedisBaseDao
复制代码
@Component
public class RedisBaseDao {
/**
* 日志记录
*/
private static Logger logger = Logger.getLogger(RedisBaseDao.class);
@Autowired
protected RedisTemplate《String, String》 redisTemplate;
public RedisTemplate《String, String》 getRedisTemplate() {
return redisTemplate;
}
/**
* 缓存value操作
* @param k
* @param v
* @param time
* @return
*/
public boolean cache(String k, Object v, long time) {
String key = k;
try {
long s=System.currentTimeMillis();
ValueOperations《String, String》 valueOps = redisTemplate.opsForValue();
valueOps.set(key, Json2Util.obj2String(v));
if (time 》 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
long e=System.currentTimeMillis();
if(e-s》2000){
logger.error("key:"+key+" redis time use"+(e-s));
} else if(logger.isDebugEnabled()){
logger.debug("key:"+key+" redis time use"+(e-s));
}
return true;
} catch (Throwable t) {
logger.error("缓存", t);
}
return false;
}
/**
* 添加list
* @Autor : xiongjinpeng jpx_011@163.com
* @Date : 2017年7月7日 下午2:37:31
* @param k
* @param v
* @param time
* @return
*/
// public boolean cacheList(String k, Collection v, long time) {
// String key = k;
// try {
// long s=System.currentTimeMillis();
// redisTemplate.delete(key);
// ListOperations《String, Object》 list=redisTemplate.opsForList();
// list.leftPushAll(key, v);
// if (time 》 0) redisTemplate.expire(key, time, TimeUnit.SECONDS);
// long e=System.currentTimeMillis();
// if(e-s》2000){
// logger.error("redis time use "+(e-s));
// }
// return true;
// } catch (Throwable t) {
// logger.error("缓存", t);
// }
// return false;
// }
// public boolean cacheList(String k, Collection v) {
// return cacheList(k, v, -1);
// }
// public 《T》 List《T》 getList(String k,int start,int end) {
// try {
// long s=System.currentTimeMillis();
// ListOperations《String, Object》 valueOps=redisTemplate.opsForList();
// List《T》 o=(List《T》) valueOps.range(k, start, end);
// long e=System.currentTimeMillis();
// if(e-s》2000){
// logger.error("redis time use "+(e-s));
// }
// return o;
// } catch (Throwable t) {
// logger.error("获取缓存失败key");
// }
// return null;
// }
// public 《T》 List《T》 getList(String k){
// return getList(k, 0, -1);
// }
/**
* 缓存value操作
* @param k
* @param v
* @return
*/
public boolean cache(String k, Object v) {
return cache(k, v, RedisUtil.keytimeout);
}
public boolean containsKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Throwable t) {
logger.error("判断缓存存在失败key");
}
return false;
}
/**
* 获取缓存
* @param k
* @return
*/
// public Object get(String k) {
// return get(k,RedisUtil.keytimeout);
// }
//
// public Object get(String k,long time) {
// try {
// long s=System.currentTimeMillis();
// ValueOperations《String, String》 valueOps = redisTemplate.opsForValue();
// Object o=valueOps.get(k);
// if (time 》 0) redisTemplate.expire(k, time, TimeUnit.SECONDS);
// long e=System.currentTimeMillis();
// if(e-s》2000){
// logger.error("key:"+k+" redis time use "+(e-s));
// } else if(logger.isDebugEnabled()){
// logger.debug("key:"+k+" redis time use"+(e-s));
// }
// return o;
// } catch (Throwable t) {
// logger.error("获取缓存失败key");
// }
// return null;
// }
public 《T》 T get(String k,Class《T》 clazz) {
return get(k,RedisUtil.keytimeout, clazz);
}
public 《T》 T get(String k,long time,Class《T》 clazz) {
try {
long s=System.currentTimeMillis();
ValueOperations《String, String》 valueOps = redisTemplate.opsForValue();
String o=valueOps.get(k);
if (time 》 0) redisTemplate.expire(k, time, TimeUnit.SECONDS);
long e=System.currentTimeMillis();
if(e-s》2000){
logger.error("key:"+k+" redis time use "+(e-s));
} else if(logger.isDebugEnabled()){
logger.debug("key:"+k+" redis time use"+(e-s));
}
if(o!=null){
return Json2Util.getObjectMapper().readValue(o, clazz);
}
} catch (Throwable t) {
logger.error("获取缓存失败key");
}
return null;
}
public 《T》 List《T》 getList(String k,long time,Class《T》 clazz) {
try {
long s=System.currentTimeMillis();
ValueOperations《String, String》 valueOps = redisTemplate.opsForValue();
String o=valueOps.get(k);
if (time 》 0) redisTemplate.expire(k, time, TimeUnit.SECONDS);
long e=System.currentTimeMillis();
if(e-s》2000){
logger.error("key:"+k+" redis time use "+(e-s));
} else if(logger.isDebugEnabled()){
logger.debug("key:"+k+" redis time use"+(e-s));
}
if(o!=null){
JavaType javaType = Json2Util.getObjectMapper().getTypeFactory().constructParametricType(List.class, clazz);
List《T》 list = Json2Util.getObjectMapper().readValue(o, javaType);
return list;
}
} catch (Throwable t) {
logger.error("获取缓存失败key");
}
return null;
}
public 《T》 List《T》 getList(String k,Class《T》 clazz) {
return getList(k, RedisUtil.keytimeout, clazz);
}
/**
* 移除缓存
* @param key
* @return
*/
public boolean remove(String key) {
try {
redisTemplate.delete(key);
return true;
} catch (Throwable t) {
logger.error("获取缓存失败key");
}
return false;
}
/**
* 模糊匹配,不建议使用,影响性能,只在一些数据重置的时候使用
* @Date : 2017年7月6日 下午4:13:45
* @param pattern
* @return
*/
@Deprecated
public Set《String》 keys(String pattern) {
try {
long s=System.currentTimeMillis();
Set《String》 keys=redisTemplate.keys(pattern);
long e=System.currentTimeMillis();
if(e-s》2000){
logger.error("redis time use "+(e-s));
}
return keys;
} catch (Throwable t) {
logger.error("获取缓存失败pattern");
}
return null;
}
public String flushDB() {
return redisTemplate.execute(new RedisCallback《String》() {
public String doInRedis(RedisConnection connection) throws DataAccessException {
connection.flushDb();
return "ok";
}
});
}
public long dbSize() {
return redisTemplate.execute(new RedisCallback《Long》() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
return connection.dbSize();
}
});
}
}
复制代码
RedisUtil
复制代码
public class RedisUtil {
//单例
private RedisUtil(){}
private static RedisBaseDao dao=null;
static {
if(dao==null){
synchronized (RedisUtil.class) {
if(dao==null){
dao=ContextUtil.getBean(RedisBaseDao.class);
try {
String keytimeoutstr=ContextUtil.getInitConfig("redis.keytimeout");
String unit=keytimeoutstr.substring(keytimeoutstr.length()-1);
Integer num=Integer.parseInt(keytimeoutstr.substring(0,keytimeoutstr.length()-1));
if(unit.equals("d")){
keytimeout=num*24*60*60;
} else if(unit.equals("h")){
keytimeout=num*60*60;
} else if(unit.equals("m")){
keytimeout=num*60;
} else if(unit.equals("s")){
keytimeout=num;
} else {
throw new RuntimeException("redis key timeout初始化失败");
}
} catch (Exception e) {
throw new RuntimeException("redis key timeout初始化失败");
}
}
}
}
}
public static RedisBaseDao getRedisDao() {
return dao;
}
public static long keytimeout=30*24*60*60;//秒
}
复制代码
使用类,
CommonCache
复制代码
public class CommonCache {
/**
* 查询缓存
* @Date : 2017年7月5日 下午3:15:47
* @param userId
* @return
*/
public static FileCache queryFileCache(Long fid){
if(fid==null){
return null;
}
String key=CachePrefix.filecache_prefix+fid;
FileCache u=RedisUtil.getRedisDao().get(key,FileCache.class);
if(u==null){
return refreshFileCache(fid);
} else {
return u;
}
}
/**
* 刷新缓存
* @Date : 2017年7月5日 下午3:15:39
* @param userId
*/
public static FileCache refreshFileCache(Long fid){
if(fid==null){
return null;
}
IBaseDao dao=ContextUtil.getBean(IBaseDao.class);
String key=CachePrefix.filecache_prefix+fid;
StringBuffer sql = new StringBuffer();
sql.append("select f.f_isdeleted,f.f_id,f.f_name,f.f_extension,f.f_type,f.f_size,f.f_create_time,f.f_oss_bucket from t_file f where f.f_id=?");
FileCache userExt = dao.queryObjectBySql(FileCache.class, sql.toString(), new Object{fid});
RedisUtil.getRedisDao().cache(key, userExt);
return userExt;
}
}
复制代码
json使用jackson个人感觉是最快的
Json2Util
复制代码
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @Description :
* @Autor : xiongjinpeng jpx_011@163.com
* @Date : 2016年1月26日 上午10:11:41
* @version :
*/
public class Json2Util {
private static ObjectMapper objectMapper=null;
static {
if(objectMapper==null){
synchronized (Json2Util.class) {
if(objectMapper==null){
objectMapper=new ObjectMapper();
objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
}
}
}
public static ObjectMapper getObjectMapper() {
return objectMapper;
}
public static String obj2String(Object obj){
String s = "";
try {
s = getObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
private Json2Util(){}
public static void main(String args) throws Exception{
}
}
复制代码
java实体类怎么转换成json
导入Google的包gson-2.2.4.jar
然后实例化Gson
static Gson gosn = new Gson();
String json = gosn.toJson(hashMap); //这里放一个对象,什么对象都可以。
转化后就是Json,功能强大很多,也简单很多。
json-lib-2.4-jdk15.jar
ezmorph-1.0.6.jar
转换的话这样用
String s= JSONArray.fromObject(user).toString();
spring-webmvc4
在方法上加入@ResponseBody,同时方法返回值为实体对象,spring会自动将对象转换为json格式,并返回到客户端
java如何返回json格式
在Java中,可以使用Jackson库将Java对象转换为JSON格式。例如,假设有一个名为person的Person对象,可以使用以下代码将其转换为JSON格式:
import com.fasterxml.jackson.databind.ObjectMapper;ObjectMapper mapper = new ObjectMapper();String json = mapper.writeValueAsString(person);
这段代码中,ObjectMapper类是Jackson库中的一个核心类,用于将Java对象转换为JSON格式。首先创建一个ObjectMapper对象,然后调用其writeValueAsString方法将Person对象转换为JSON格式的字符串。最后将该字符串返回即可。
需要注意的是,如果要将Java对象转换为JSON格式,需要为该对象添加getter方法,以便ObjectMapper类能够访问该对象的属性。另外,需要在pom.xml文件中添加Jackson库的依赖,例如:
《dependency》《groupId》com.fasterxml.jackson.core《/groupId》《artifactId》jackson-databind《/artifactId》《version》2.12.3《/version》《/dependency》
jackson怎么将list转为json字符串
Jackson处理一般的JavaBean和Json之间的转换只要使用ObjectMapper 对象的readValue和writeValueAsString两个方法就能实现。但是如果要转换复杂类型Collection如 List《YourBean》,那么就需要先反序列化复杂类型 为泛型的Collection Type。
如果是ArrayList《YourBean》那么使用ObjectMapper 的getTypeFactory().constructParametricType(collectionClass, elementClasses);
如果是HashMap《String,YourBean》那么 ObjectMapper 的getTypeFactory().constructParametricType(HashMap.class,String.class, YourBean.class);
public final ObjectMapper mapper = new ObjectMapper();
public static void main(String args) throws Exception{
JavaType javaType = getCollectionType(ArrayList.class, YourBean.class);
List《YourBean》 lst = (List《YourBean》)mapper.readValue(jsonString, javaType);
}
/**
* 获取泛型的Collection Type
* @param collectionClass 泛型的Collection
* @param elementClasses 元素类
* @return JavaType Java类型
* @since 1.0
*/
public static JavaType getCollectionType(Class《?》 collectionClass, Class《?》... elementClasses) {
return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}

本文相关文章:
全局变量在所有的函数中都可以使用(c语言中定义的全局变量,在某个函数中赋值还能被其他函数使用吗)
2025年8月12日 07:45
win10的java环境变量设置(win10的java环境变量怎么设置)
2025年8月8日 19:15
数组初始化的定义不同之处(5.数组有什么特点数组的声明和初始化方法与筒单变量有什么不同)
2025年8月4日 08:00
python编程实例详解(python函数变量及代码利用是什么python函数变量及代码利用说明)
2025年8月3日 06:00
审计的随机数表法(审计抽样的统计抽样和非统计抽样有啥区别跟属性抽样和变量抽样是什么关系)
2025年7月27日 09:45
python 判断变量类型(怎么查看变量的类型 python)
2025年7月19日 21:00
更多文章:
switch case用法举例python(为什么Python中没有Switch/Case语句)
2025年9月27日 18:45
checkbox 选中事件(js动态生成的checkbox取值和选中事件)
2025年9月26日 11:00
用数据库做管理系统(何谓数据库管理系统简述数据库管理系统的功能)
2026年7月20日 19:30
个人述职报告ppt(简约彩色个人述职报告PPT模板最新怎么样)
2025年9月19日 22:30
驽马十驾的故事(“驽马十驾,功在不舍”是什么意思古代早有“龟兔赛跑”的故事!)
2025年8月1日 23:30
memory lapse是什么意思?collapse;是什么意思
2026年5月28日 23:45
delphi三层数据库技术(delphi 多个数据库使用一个三层问题)
2025年12月4日 01:45
count函数怎么统计文字(count如何计算同一种颜色的文字)
2025年6月1日 12:45
java打印爱心图案的代码(html爱心代码用devc++能打出来嘛)
2026年8月5日 05:00
python如何使用多线程(Python的keyboard模块使用多线程)
2026年9月14日 03:00











