Java学习总结--json

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 void 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();		
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值