JAVA 处理JSON工具类

以下代码为Java处理json数据的工具类,以备后用

package com.json.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtils {
 
  public static String encodeList(Object[] objs) {
    return encodeList(Arrays.asList(objs));
  }

  @SuppressWarnings("unchecked")
  public static String encodeList(Collection objs) {
    JSONArray list = new JSONArray();
    if (objs == null || objs.size() == 0)
      return list.toString();
    for (Object ae : objs) {
      list.add(ae);
    }
    return list.toString();
  }
 
  @SuppressWarnings("unchecked")
  public static String encodeObject(Object obj){
    if(obj instanceof Collection)
      return encodeList((Collection)obj);
    JSONObject jo = JSONObject.fromObject(obj);
    return jo.toString();
  }
 
  @SuppressWarnings("unchecked")
  public static <T>List<T> decodeList(String str, Class<T> clazz) {
    if (str == null || "".equals(str))
      return null;
    JSONArray obj = JSONArray.fromObject(str);
    Object[] rts = obj.toArray();
    List<T> result = new ArrayList<T>(rts.length);
    for (int i = 0; i < rts.length; i++) {
      Object jo = rts[i];
      T ele = (T)JSONObject.toBean((JSONObject) jo, clazz);
      result.add( ele );
    }
    return result;
  }
 
  @SuppressWarnings("unchecked")
  public static <T>T decodeObject(String json,Class<T> clz){
    JSONObject jsonObject = JSONObject.fromObject(json);
    T bean = (T) JSONObject.toBean(jsonObject, clz);
    return bean;
  }
}

你可能感兴趣的:(java,json,utils)