响应对象转json时属性名大小写问题完美解决

首先:案例是model里的属性名大写,http response时json默认变成小写开头,和model属性不一致。

例子:

model为:
class User{
    private String NAME;
    private int AGE;
    getter 和 setter...
}

http 请求后响应的json为:
{
    "name":"张三",
    "age":20
}


业务需求json为:
{
    "NAME":"张三",
    "AGE":20
}


可行的解决方案:

网上搜了好多,大部分都是在属性上添加@JsonProperty("XXX"),但是这里就又出现了个问题,转json后会有两个同名但大小写不一样的属性;? 就又去搜索,说是在getter方法上添加@JsonProperty("XXX"),解决了,但是字段少没问题,咱每个实体model上添加下,如果字段多了呢?实体多了呢?

完美的解决方案:

本人自己推敲的,分享给大家,好用就用,不好用请忽略,当然肯定有其他更好的,有知道的请文末留言告知博主,非常感谢?

下面上方法代码:

响应json前将对象传入此方法即可

    /**
     * 对象转json时属性变大写
     *
     * @param entity
     * @return
     */
    public static Map<String,Object> object2UpperCase(Object entity){
        Map<String,Object> res = Maps.newHashMap();
        if (null==entity){
            return res;
        }
        //将对象的属性转化为大写
        String json = JacksonUtil.bean2Json(entity);
        Map<String,Object> map = JacksonUtil.json2Map(json,String.class,Object.class);
        if (null!=map && !map.isEmpty()){
            for(Map.Entry<String,Object> entry:map.entrySet()){
                /**
                 * TODO-关键在这里根据业务需要转大小写
                 */
                res.put(entry.getKey().toUpperCase(),entry.getValue());
            }
        }
        return res;
    }
JacksonUtil.java json转化工具类
package com.ww.common.json;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


/**
 * json转化工具
 * @author Ace Lee
 * 
 */
public  class JacksonUtil {
	
	
	private static final ObjectMapper MAPPER = new ObjectMapper();

	static {
		//MAPPER.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, false);
		MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
		MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
		MAPPER.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES,true);
	}


	private static final JsonFactory JSONFACTORY = new JsonFactory();
	

	/**
	 * 把json参数转换成对应Vo
	 * <B>第二个参数请使用  Class ,比如JacksonUtil.json2Bean("{\"name\":\"0000\",\"age\":456}", Car.class);</B>
	 * @param json
	 * @param valueTypeRef
	 * @return
	 */
	public static <T> T json2Bean(String json, TypeReference<T> valueTypeRef) {
		
		T rtn =null;
		try {
			rtn = 	MAPPER.readValue(json, valueTypeRef);
		} catch (JsonParseException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return rtn;
	}
	public static <T> T json2Bean(String json, Class<T>  cls) {
	    
	    T rtn =null;
	    try {
	        rtn = 	MAPPER.readValue(json, cls);
	    } catch (JsonParseException e) {
	        throw new RuntimeException(e);
	    } catch (JsonMappingException e) {
	        throw new RuntimeException(e);
	    } catch (IOException e) {
	        throw new RuntimeException(e);
	    }
	    return rtn;
	}

	
	
	/**
	 * 转换vo 为 json
	 */
	public static String bean2Json(Object o) {
	    StringWriter sw = new StringWriter();
	    JsonGenerator jsonGenerator = null;
	    
	    try {
	        jsonGenerator = JSONFACTORY.createJsonGenerator(sw);
	        MAPPER.writeValue(jsonGenerator, o);
	        return sw.toString();
	        
	    } catch (Exception e) {
	        throw new  RuntimeException(e);
	        //return null;
	        
	    } finally {
	        if (jsonGenerator != null) {
	            try {
	                jsonGenerator.close();
	            } catch (Exception e) {
	                throw  new RuntimeException(e);
	            }
	        }
	    }
	}
	/**
	 * 转换vo 为 json
	 */
	public static String bean2Json(Object o,ObjectMapper mapper) {
	    StringWriter sw = new StringWriter();
	    JsonGenerator jsonGenerator = null;
	    
	    try {
	        jsonGenerator = JSONFACTORY.createJsonGenerator(sw);
	        mapper.writeValue(jsonGenerator, o);
	        return sw.toString();
	        
	    } catch (Exception e) {
	        throw new  RuntimeException(e);
	        //return null;
	        
	    } finally {
	        if (jsonGenerator != null) {
	            try {
	                jsonGenerator.close();
	            } catch (Exception e) {
	                throw  new RuntimeException(e);
	            }
	        }
	    }
	}
	/**
	 * 转换vo 为 json,属性为null不被序列化
	 */
	public static String bean2JsonWithoutNull(Object o) {
		StringWriter sw = new StringWriter();
		JsonGenerator jsonGenerator = null;
		ObjectMapper mapper=new ObjectMapper();
		mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		try {
			jsonGenerator = JSONFACTORY.createJsonGenerator(sw);
            mapper.writeValue(jsonGenerator, o);
			return sw.toString();

		} catch (Exception e) {
			throw new  RuntimeException(e);
			//return null;

		} finally {
			if (jsonGenerator != null) {
				try {
					jsonGenerator.close();
				} catch (Exception e) {
					throw  new RuntimeException(e);
				}
			}
		}
	}
	
	

	/**
	 * 转换Json String 为 HashMap
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> json2Map(String json,
			boolean collToString) {
		try {
			Map<String, Object> map = MAPPER.readValue(json, HashMap.class);
			if (collToString) {
				for (Map.Entry<String, Object> entry : map.entrySet()) {
					if (entry.getValue() instanceof Collection
							|| entry.getValue() instanceof Map) {
						entry.setValue(bean2Json(entry.getValue()));
					}
				}
			}
			return map;
		} catch (Exception e) {
			//return null;
			throw new RuntimeException(e);
		}
	}
	/**
	 * json String转换为Map
	 * @author dingyiming@chinasofti.com
	 * @date 2016年1月5日 下午9:12:06
	 * @param json
	 * @param clk - key的类型
	 * @param clv - value的类型
	 * @return 
	 * @description
	 */
	public static <K,V> Map<K, V> json2Map(String json,Class<K> clk,Class<V> clv) {
		try {
			JavaType javaType = MAPPER.getTypeFactory().constructMapType(Map.class, clk, clv);
			Map<K, V> map = MAPPER.readValue(json, javaType);
			return map;
		} catch (Exception e) {
			//return null;
			throw new RuntimeException(e);
		}
	}	
	/**
	 * json String转换为ConcurrentMap
	 * @author dingyiming@chinasofti.com
	 * @date 2016年1月5日 下午9:12:06
	 * @param json
	 * @param clk - key的类型
	 * @param clv - value的类型
	 * @return 
	 * @description
	 */
	public static <K,V> ConcurrentMap<K, V> json2ConMap(String json,Class<K> clk,Class<V> clv) {
		try {
			JavaType javaType = MAPPER.getTypeFactory().constructMapType(ConcurrentHashMap.class, clk, clv);
			ConcurrentMap<K, V> map = MAPPER.readValue(json, javaType);
			return map;
		} catch (Exception e) {
			//return null;
			throw new RuntimeException(e);
		}
	}

	@SuppressWarnings("serial")
	public static class jsonParseException extends Exception {
		public jsonParseException(String message) {
			super(message);
		} 
	}

	/**
	 * List 转换成json
	 * 
	 * @param list
	 * @return
	 */
	public static String list2Json(List<Map<String, String>> list) {
		JsonGenerator jsonGenerator = null;
		StringWriter sw = new StringWriter();
		try {
			jsonGenerator = JSONFACTORY.createJsonGenerator(sw);
			new ObjectMapper().writeValue(jsonGenerator, list);
			jsonGenerator.flush();
			return sw.toString();
		} catch (Exception e) {
			//return null;
			throw new  RuntimeException(e);
		} finally {
			if (jsonGenerator != null) {
				try {
					jsonGenerator.flush();
					jsonGenerator.close();
				} catch (Exception e) {
					//e.printStackTrace();
					throw new  RuntimeException(e);
				}
			}
		}
	}

	/**
	 * json 转List
	 * 
	 * @param json
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<Map<String, String>> json2List(String json) {
		try {
			if (json != null && !"".equals(json.trim())) {
				JsonParser jsonParse = JSONFACTORY
						.createJsonParser(new StringReader(json));

				ArrayList<Map<String, String>> arrayList = (ArrayList<Map<String, String>>) new ObjectMapper()
						.readValue(jsonParse, ArrayList.class);
				return arrayList;
			} else {
				return null;
			}
		} catch (Exception e) {
			//return null;
			throw  new RuntimeException(e);
			
		}
	}
	
	
	// 测试方法
	public static void main(String[] args) {
//		User user = new User();
//		user.setId(1);
//		user.setUsername("张小三");
//		user.setAddress("海南");
//		user.setPhone("010");
//
//		User user2 = new User();
//		user2.setId(2);
//		user2.setUsername("李小璐");
//		user2.setAddress("天津");
//		user2.setPhone("8888888");
//
//		List<User> list = new ArrayList<User>();
//		list.add(user);
//		list.add(user2);
//
//		 String str = bean2Json(user);
//		 bean2Json(list);
//		 System.out.println(str);
//
//		 String json =
//		 "{\"address\":\"拾金路\",\"id\":1,\"username\":\"张小宁\",\"phone\":123456789}";
//		 User u = (User)json2Bean(json,new TypeReference<User>() {
//        });
//		 System.out.println(u);
		String str="{\"naturalPerson\":{\"queryOrangeScoreDetail\":{\"acctLevel\":null,\"behavPref\":null,\"creditHis\":null,\"mobileNo\":null,\"orangeScore\":null,\"repayCap\":null,\"socialRela\":null,\"updatedAt\":null}}}";
		Map<String, Object> map = JacksonUtil.json2Map(str, String.class, Object.class);
		System.out.println(map);
	}
	
	
	static class   User {
		 
		 private int id;
		 private String username;
		 private String address;
		 private String phone;
		 public int getId() {
		  return id;
		 }
		 public void setId(int id) {
		  this.id = id;
		 }
		 public String getUsername() {
		  return username;
		 }
		 public void setUsername(String username) {
		  this.username = username;
		 }
		 public String getAddress() {
		  return address;
		 }
		 public void setAddress(String address) {
		  this.address = address;
		 }
		 public String getPhone() {
		  return phone;
		 }
		 public void setPhone(String phone) {
		  this.phone = phone;
		 }
		 
		 @Override
		 public String toString() {
		  return "id: " + id + " username: " + username + " address: " + address + " phone: " + phone;
		 }
		}
	
}

另附上jackson的pom依赖

注意三个版本号必须保持一致

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.3</version>
        </dependency>

有更好的方案,欢迎留言,再次感谢! 

 

 

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值