您的位置:首页 > Web前端 > JavaScript

阿里的json处理--fastjson

2016-10-26 17:20 357 查看
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;

/**
* json工具
*/
public class JsonUtil {

/**
* 对象转 json
*/
public static String toJson( Object o ){
return JSON.toJSONString( o );
}

/**
* json转对象
*/
public static <T> T toObject( String json , Class<T> clazz ){
return JSON.parseObject( json, clazz );
}
/**
* json转list对象
*/
public static <T> List<T> toListObject(String json, Class<T> clazz ){
return JSON.parseArray( json, clazz);
}

/**
* json转Map(支持多层级)
*/
@SuppressWarnings( "unchecked")
public static Map<String, Object> toMap( String json ){
Map<String, Object> m = new HashMap<String, Object>();
try{
m = toObject( json, HashMap. class );
for( String k : m .keySet() ){
Object v = m.get( k );
if( v != null ){
String valStr = String. valueOf( v );
if( valStr .startsWith( "{" ) && valStr.endsWith( "}" )  ){
m.put( k, toMap( valStr ) );
}
}
}
} catch( Exception e ){

}
return m ;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json fastjson