package com.huarun.project.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
/***
* List 转 json
*
* @author Administrator
*
*/
public class JsonMapper extends ObjectMapper{
private static final long serialVersionUID = 1L;
private static JsonMapper mapper;
/**
* 允许单引号
* 允许不带引号的字段名称
*/
public JsonMapper enableSimple() {
this.configure(Feature.ALLOW_SINGLE_QUOTES, true);
this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
return this;
}
public static JsonMapper getInstance() {
if (mapper == null){
mapper = new JsonMapper().enableSimple();
}
return mapper;
}
/***
* 如果对象为Null,返回"null". 如果集合为空集合,返回"[]".
*
* @param object
* @return
*/
public String toJson(Object object) {
try {
return this.writeValueAsString(object);
} catch (IOException e) {
return null;
}
}
/**
* 测试 list 转 json
*/
public static void main(String[] args) {
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("id", 1);
map.put("pId", -1);
map.put("name", "根节点");
list.add(map);
map = Maps.newHashMap();
map.put("id", 2);
map.put("pId", 1);
map.put("name", "你好");
map.put("open", true);
list.add(map);
Map<String, Object> map3 = new HashMap<>();
map3.put("A1", 5);
map3.put("B1", 5);
map3.put("C1", 5);
list.add(map3);
//方法1
String json = JsonMapper.getInstance().toJson(list);
System.out.println(json);
//方法2
JSONArray subMsgs = JSONArray.fromObject(list);
System.out.println(subMsgs);
//JSONObject 测试
JSONObject jsono = new JSONObject();
jsono.put("age", "888");
jsono.putAll(map);
System.out.println(jsono);
//Map 接收
Map<String,Object> strmap=new JSONObject();
strmap.put("group", "员工");
strmap.put("from", "深圳");
strmap.put("id", 33);
System.out.println(strmap);
//json 字符串 转 json 对象
JSONObject json1 = JSONObject.fromObject(json);
System.out.println(json1);
}
}