Java学习总结--json
2015-10-12 14:33
330 查看
1.json的应用
json的应用比较广泛,比如javaweb前后台参数传递,移动应用参数传递等。2.json与列表相互转化
需要jar包:jackson-core-asl-1.9.2.jar
jackson-mapper-asl-1.9.2.jar
/** * 装换为json格式字符串 * @param obj * @return */ public static String toJson(Object obj) { try { return jsonMapper.writeValueAsString(obj); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * @param json:json数据格式的数组 * @param clazz:实体类 * @return */ @SuppressWarnings("unchecked") public static List jsonToList(String json, Class<?> clazz){ try { List list = new ArrayList(); List mapList = jsonMapper.readValue(json, List.class); for (int i = 0; i < mapList.size(); i++) { LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) mapList.get(i); Object obj = clazz.newInstance(); Field[] fileds = obj.getClass().getDeclaredFields(); for (Field field : fileds) { String name = field.getName(); if(map.containsKey(name) && map.get(name)!= null){ //json会把原来的Date类型转换成时间戳,Float装换成Double if(field.getType().equals(Date.class)){ Long l = (Long) map.get(name); Date d = DateUtil.convertTimestampToDate(l); RefUtils.invokeSetterMethod(obj, name, field.getType(),d); }else if(field.getType().equals(Float.class)){ Double f = (Double)(Object)map.get(name); RefUtils.invokeSetterMethod(obj, name, field.getType(), f.floatValue()); }else{ RefUtils.invokeSetterMethod(obj, name, field.getType(), map.get(name)); } } } list.add(obj); } return list; } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
3.json工具类和测试类
测试类中简单引入jsonObject和jsonArray,因此需要额外的jar:commons-beanutils-1.8.0.jar
commons-collections-3.2.jar
commons-lang-2.4.jar
commons-logging-1.2.jar
ezmorph-1.0.4.jar
json-lib-2.2.2-jdk15.jar
JsonUtil:json工具类
package com.sangbill.advanced.json;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import com.sangbill.advanced.date.DateUtil;
public class JsonUtil {
private static ObjectMapper jsonMapper = new ObjectMapper();
/** * 装换为json格式字符串 * @param obj * @return */ public static String toJson(Object obj) { try { return jsonMapper.writeValueAsString(obj); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * @param json:json数据格式的数组 * @param clazz:实体类 * @return */ @SuppressWarnings("unchecked") public static List jsonToList(String json, Class<?> clazz){ try { List list = new ArrayList(); List mapList = jsonMapper.readValue(json, List.class); for (int i = 0; i < mapList.size(); i++) { LinkedHashMap<String, Object> map = (LinkedHashMap<String, Object>) mapList.get(i); Object obj = clazz.newInstance(); Field[] fileds = obj.getClass().getDeclaredFields(); for (Field field : fileds) { String name = field.getName(); if(map.containsKey(name) && map.get(name)!= null){ //json会把原来的Date类型转换成时间戳,Float装换成Double if(field.getType().equals(Date.class)){ Long l = (Long) map.get(name); Date d = DateUtil.convertTimestampToDate(l); RefUtils.invokeSetterMethod(obj, name, field.getType(),d); }else if(field.getType().equals(Float.class)){ Double f = (Double)(Object)map.get(name); RefUtils.invokeSetterMethod(obj, name, field.getType(), f.floatValue()); }else{ RefUtils.invokeSetterMethod(obj, name, field.getType(), map.get(name)); } } } list.add(obj); } return list; } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
}
RefUtils:反射工具类
package com.sangbill.advanced.json; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.sun.xml.internal.ws.util.StringUtils; public abstract class RefUtils { /** * 调用Setter方法. * @throws Exception */ public static Object invokeSetterMethod(Object obj, String propertyName,final Class<?> parameterTypes,Object value) throws Exception { String setterMethodName = "set" + StringUtils.capitalize(propertyName); return invokeMethod(obj, setterMethodName,new Class[]{parameterTypes}, new Object[] {value}); } /** * 调用Getter方法. * @throws Exception */ public static Object invokeGetterMethod(Object obj, String propertyName) throws Exception { String getterMethodName = "get" + StringUtils.capitalize(propertyName); return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {}); } public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes, final Object[] args) throws Exception { Method method = getAccessibleMethod(obj, methodName, parameterTypes); if (method == null) { throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]"); } try { return method.invoke(obj, args); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } } public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) { if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException || e instanceof NoSuchMethodException) { return new IllegalArgumentException("Reflection Exception.", e); } else if (e instanceof InvocationTargetException) { return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException()); } else if (e instanceof RuntimeException) { return (RuntimeException) e; } return new RuntimeException("Unexpected Checked Exception.", e); } public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) { //Assert.notNull(obj, "object不能为空"); for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { Method method = superClass.getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); return method; } catch (NoSuchMethodException e) {//NOSONAR // Method不在当前类定义,继续向上转型 } } return null; } }User:实体类
package com.sangbill.advanced.json; import java.util.Date; public class User { private Long id; private Integer age; private Float count; private Double point; private Boolean isMember; private String name; private String passwd; private Date birthday; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Float getCount() { return count; } public void setCount(Float count) { this.count = count; } public Double getPoint() { return point; } public void setPoint(Double point) { this.point = point; } public Boolean getIsMember() { return isMember; } public void setIsMember(Boolean isMember) { this.isMember = isMember; } public String getName() { return name; } public vo 4000 id setName(String name) { this.name = name; } public String getPasswd() { return passwd; } public void setPasswd(String passwd) { this.passwd = passwd; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
Test:测试类
package com.sangbill.advanced.json; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class Test { public static void main(String[] args) { int size = 10; List<User> userList = getUserList(size); String str = JsonUtil.toJson(userList); System.out.println(str); List list = JsonUtil.jsonToList(str,User.class); print(null, list, null); //jsonArray的装换 JSONArray arr = JSONArray.fromObject(str); System.out.println(arr.size()); JSONObject obj = (JSONObject) arr.get(0); obj.get("id"); } private static void print(String properties, List<User> userList,String order) { System.out.println("order by "+properties+" "+order); for (User user : userList) { System.out.println(String.format("Id:%-20d ,age:%-2d, count:%-5f, point:%-5f, isMenber:%-5b, name:%-10s, passwd:%-10s", user.getId(),user.getAge(),user.getCount(),user.getPoint(),user.getIsMember(),user.getName(),user.getPasswd())); } System.out.println("\n\n"); } /** * get random userList * @param size * @return */ private static List<User> getUserList(int size) { List<User> userList = new ArrayList<User>(); for (int i = 0; i < size; i++) { User u = getUser(); userList.add(u); } return userList; } /** * get random user * @return */ private static User getUser() { User u = new User(); Random r = new Random(); boolean[] results = {true,false}; u.setId(r.nextLong()); u.setAge(r.nextInt(100)); u.setCount(r.nextFloat()); u.setPoint(r.nextDouble()); u.setIsMember(results[r.nextInt(2)]); u.setName(getString()); u.setPasswd(getString()); u.setBirthday(new Date()); return u; } /** * get random String * @return */ private static String getString(){ String s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; Random r = new Random(); int length = r.nextInt(10)+1; int sLength = s.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { sb.append(s.charAt(r.nextInt(sLength))); } return sb.toString(); } }
相关文章推荐
- XML 与 JSON 优劣对比
- VBA将excel数据表生成JSON文件
- newtonsoft.json解析天气数据出错解决方法
- vbs 解析json jsonp的方法
- Extjs4如何处理后台json数据中日期和时间
- C#实现将类的内容写成JSON格式字符串的方法
- JQuery ajax返回JSON时的处理方式 (三种方式)
- jquery JSON的解析方式示例介绍
- c#版json数据解析示例分享
- ASP JSON类文件的使用方法
- C#实现对Json字符串处理实例
- C#实现Json转Unicode的方法
- php解析json数据实例
- PHP中JSON的应用技巧
- PHP6 先修班 JSON实例代码
- 关于JSON以及JSON在PHP中的应用技巧
- .Net中的json操作类用法分析
- C#操作 JSON方法汇总
- JavaScript中字符串(string)转json的2种方法
- js Object2String方便查看js对象内容