代碼如下
目前成都創(chuàng)新互聯(lián)公司已為上千余家的企業(yè)提供了網(wǎng)站建設(shè)、域名、網(wǎng)站空間、網(wǎng)站運(yùn)營(yíng)、企業(yè)網(wǎng)站設(shè)計(jì)、麻城網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class JsonValidator {
private CharacterIterator it;
private char c;
private int col;
public JsonValidator(){
}
/**
* 驗(yàn)證一個(gè)字符串是否是合法的JSON串
*
* @param input 要驗(yàn)證的字符串
* @return true-合法 ,false-非法
*/
public boolean validate(String input) {
input = input.trim();
boolean ret = valid(input);
return ret;
}
private boolean valid(String input) {
if ("".equals(input)) return true;
boolean ret = true;
it = new StringCharacterIterator(input);
c = it.first();
col = 1;
if (!value()) {
ret = error("value", 1);
} else {
skipWhiteSpace();
if (c != CharacterIterator.DONE) {
ret = error("end", col);
}
}
return ret;
}
private boolean value() {
return literal("true") || literal("false") || literal("null") || string() || number() || object() || array();
}
private boolean literal(String text) {
CharacterIterator ci = new StringCharacterIterator(text);
char t = ci.first();
if (c != t) return false;
int start = col;
boolean ret = true;
for (t = ci.next(); t != CharacterIterator.DONE; t = ci.next()) {
if (t != nextCharacter()) {
ret = false;
break;
}
}
nextCharacter();
if (!ret) error("literal " + text, start);
return ret;
}
private boolean array() {
return aggregate('[', ']', false);
}
private boolean object() {
return aggregate('{', '}', true);
}
private boolean aggregate(char entryCharacter, char exitCharacter, boolean prefix) {
if (c != entryCharacter) return false;
nextCharacter();
skipWhiteSpace();
if (c == exitCharacter) {
nextCharacter();
return true;
}
for (;;) {
if (prefix) {
int start = col;
if (!string()) return error("string", start);
skipWhiteSpace();
if (c != ':') return error("colon", col);
nextCharacter();
skipWhiteSpace();
}
if (value()) {
skipWhiteSpace();
if (c == ',') {
nextCharacter();
} else if (c == exitCharacter) {
break;
} else {
return error("comma or " + exitCharacter, col);
}
} else {
return error("value", col);
}
skipWhiteSpace();
}
nextCharacter();
return true;
}
private boolean number() {
if (!Character.isDigit(c) c != '-') return false;
int start = col;
if (c == '-') nextCharacter();
if (c == '0') {
nextCharacter();
} else if (Character.isDigit(c)) {
while (Character.isDigit(c))
nextCharacter();
} else {
return error("number", start);
}
if (c == '.') {
nextCharacter();
if (Character.isDigit(c)) {
while (Character.isDigit(c))
nextCharacter();
} else {
return error("number", start);
}
}
if (c == 'e' || c == 'E') {
nextCharacter();
if (c == '+' || c == '-') {
nextCharacter();
}
if (Character.isDigit(c)) {
while (Character.isDigit(c))
nextCharacter();
} else {
return error("number", start);
}
}
return true;
}
private boolean string() {
if (c != '"') return false;
int start = col;
boolean escaped = false;
for (nextCharacter(); c != CharacterIterator.DONE; nextCharacter()) {
if (!escaped c == '\\') {
escaped = true;
} else if (escaped) {
if (!escape()) {
return false;
}
escaped = false;
} else if (c == '"') {
nextCharacter();
return true;
}
}
return error("quoted string", start);
}
private boolean escape() {
int start = col - 1;
if (" \\\"/bfnrtu".indexOf(c) 0) {
return error("escape sequence \\\",\\\\,\\/,\\b,\\f,\\n,\\r,\\t or \\uxxxx ", start);
}
if (c == 'u') {
if (!ishex(nextCharacter()) || !ishex(nextCharacter()) || !ishex(nextCharacter())
|| !ishex(nextCharacter())) {
return error("unicode escape sequence \\uxxxx ", start);
}
}
return true;
}
private boolean ishex(char d) {
return "0123456789abcdefABCDEF".indexOf(c) = 0;
}
private char nextCharacter() {
c = it.next();
++col;
return c;
}
private void skipWhiteSpace() {
while (Character.isWhitespace(c)) {
nextCharacter();
}
}
private boolean error(String type, int col) {
System.out.printf("type: %s, col: %s%s", type, col, System.getProperty("line.separator"));
return false;
}
public static void main(String[] args){
String jsonStr = "{\"website\":\"open-open.com\"}";
System.out.println(jsonStr+":"+new JsonValidator().validate(jsonStr));
}
}
java可以使用JSONObject和JSONArray來(lái)操作json對(duì)象和json數(shù)組,具體用法如下
1:java對(duì)象與json串轉(zhuǎn)換:
java對(duì)象—json串:
JSONObject JSONStr = JSONObject.fromObject(object);
String str = JSONStr.toString();
json串—java對(duì)象:
JSONObject jsonObject = JSONObject.fromObject( jsonString );
Object pojo = JSONObject.toBean(jsonObject,pojoCalss);
2:java數(shù)組對(duì)象與json串轉(zhuǎn)換:
java數(shù)組—json串:
JSONArray arrayStr = JSONArray.fromObject(List?);
String str = arrayStr.toString();
json串—java數(shù)組:
JSONArray array = JSONArray.fromObject(str);
List? list = JSONArray.toList(array, ?.class);
java中將數(shù)據(jù)封裝為JSON包,可以使用java提供的jsonArray這個(gè)工具類進(jìn)行轉(zhuǎn)換,代碼如下:
package com.json;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
public class JSONUtils
{
/**
*
* @author wangwei JSON工具類
* @param T
*
*/
/***
* 將List對(duì)象序列化為JSON文本
*/
public static T String toJSONString(ListT list)
{
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
}
/***
* 將對(duì)象序列化為JSON文本
* @param object
* @return
*/
public static String toJSONString(Object object)
{
JSONArray jsonArray = JSONArray.fromObject(object);
return jsonArray.toString();
}
/***
* 將JSON對(duì)象數(shù)組序列化為JSON文本
* @param jsonArray
* @return
*/
public static String toJSONString(JSONArray jsonArray)
{
return jsonArray.toString();
}
/***
* 將JSON對(duì)象序列化為JSON文本
* @param jsonObject
* @return
*/
public static String toJSONString(JSONObject jsonObject)
{
return jsonObject.toString();
}
/***
* 將對(duì)象轉(zhuǎn)換為L(zhǎng)ist對(duì)象
* @param object
* @return
*/
public static List toArrayList(Object object)
{
List arrayList = new ArrayList();
JSONArray jsonArray = JSONArray.fromObject(object);
Iterator it = jsonArray.iterator();
while (it.hasNext())
{
JSONObject jsonObject = (JSONObject) it.next();
Iterator keys = jsonObject.keys();
while (keys.hasNext())
{
Object key = keys.next();
Object value = jsonObject.get(key);
arrayList.add(value);
}
}
return arrayList;
}
/***
* 將對(duì)象轉(zhuǎn)換為Collection對(duì)象
* @param object
* @return
*/
public static Collection toCollection(Object object)
{
JSONArray jsonArray = JSONArray.fromObject(object);
return JSONArray.toCollection(jsonArray);
}
/***
* 將對(duì)象轉(zhuǎn)換為JSON對(duì)象數(shù)組
* @param object
* @return
*/
public static JSONArray toJSONArray(Object object)
{
return JSONArray.fromObject(object);
}
/***
* 將對(duì)象轉(zhuǎn)換為JSON對(duì)象
* @param object
* @return
*/
public static JSONObject toJSONObject(Object object)
{
return JSONObject.fromObject(object);
}
/***
* 將對(duì)象轉(zhuǎn)換為HashMap
* @param object
* @return
*/
public static HashMap toHashMap(Object object)
{
HashMapString, Object data = new HashMapString, Object();
JSONObject jsonObject = JSONUtils.toJSONObject(object);
Iterator it = jsonObject.keys();
while (it.hasNext())
{
String key = String.valueOf(it.next());
Object value = jsonObject.get(key);
data.put(key, value);
}
return data;
}
/***
* 將對(duì)象轉(zhuǎn)換為L(zhǎng)istMapString,Object
* @param object
* @return
*/
// 返回非實(shí)體類型(MapString,Object)的List
public static ListMapString, Object toList(Object object)
{
ListMapString, Object list = new ArrayListMapString, Object();
JSONArray jsonArray = JSONArray.fromObject(object);
for (Object obj : jsonArray)
{
JSONObject jsonObject = (JSONObject) obj;
MapString, Object map = new HashMapString, Object();
Iterator it = jsonObject.keys();
while (it.hasNext())
{
String key = (String) it.next();
Object value = jsonObject.get(key);
map.put((String) key, value);
}
list.add(map);
}
return list;
}
/***
* 將JSON對(duì)象數(shù)組轉(zhuǎn)換為傳入類型的List
* @param T
* @param jsonArray
* @param objectClass
* @return
*/
public static T ListT toList(JSONArray jsonArray, ClassT objectClass)
{
return JSONArray.toList(jsonArray, objectClass);
}
/***
* 將對(duì)象轉(zhuǎn)換為傳入類型的List
* @param T
* @param jsonArray
* @param objectClass
* @return
*/
public static T ListT toList(Object object, ClassT objectClass)
{
JSONArray jsonArray = JSONArray.fromObject(object);
return JSONArray.toList(jsonArray, objectClass);
}
/***
* 將JSON對(duì)象轉(zhuǎn)換為傳入類型的對(duì)象
* @param T
* @param jsonObject
* @param beanClass
* @return
*/
public static T T toBean(JSONObject jsonObject, ClassT beanClass)
{
return (T) JSONObject.toBean(jsonObject, beanClass);
}
/***
* 將將對(duì)象轉(zhuǎn)換為傳入類型的對(duì)象
* @param T
* @param object
* @param beanClass
* @return
*/
public static T T toBean(Object object, ClassT beanClass)
{
JSONObject jsonObject = JSONObject.fromObject(object);
return (T) JSONObject.toBean(jsonObject, beanClass);
}
/***
* 將JSON文本反序列化為主從關(guān)系的實(shí)體
* @param T 泛型T 代表主實(shí)體類型
* @param D 泛型D 代表從實(shí)體類型
* @param jsonString JSON文本
* @param mainClass 主實(shí)體類型
* @param detailName 從實(shí)體類在主實(shí)體類中的屬性名稱
* @param detailClass 從實(shí)體類型
* @return
*/
public static T, D T toBean(String jsonString, ClassT mainClass,
String detailName, ClassD detailClass)
{
JSONObject jsonObject = JSONObject.fromObject(jsonString);
JSONArray jsonArray = (JSONArray) jsonObject.get(detailName);
T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
ListD detailList = JSONUtils.toList(jsonArray, detailClass);
try
{
BeanUtils.setProperty(mainEntity, detailName, detailList);
}
catch (Exception ex)
{
throw new RuntimeException("主從關(guān)系JSON反序列化實(shí)體失敗!");
}
return mainEntity;
}
/***
* 將JSON文本反序列化為主從關(guān)系的實(shí)體
* @param T泛型T 代表主實(shí)體類型
* @param D1泛型D1 代表從實(shí)體類型
* @param D2泛型D2 代表從實(shí)體類型
* @param jsonString JSON文本
* @param mainClass 主實(shí)體類型
* @param detailName1 從實(shí)體類在主實(shí)體類中的屬性
* @param detailClass1 從實(shí)體類型
* @param detailName2 從實(shí)體類在主實(shí)體類中的屬性
* @param detailClass2 從實(shí)體類型
* @return
*/
public static T, D1, D2 T toBean(String jsonString, ClassT mainClass,
String detailName1, ClassD1 detailClass1, String detailName2,
ClassD2 detailClass2)
{
JSONObject jsonObject = JSONObject.fromObject(jsonString);
JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);
T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
ListD1 detailList1 = JSONUtils.toList(jsonArray1, detailClass1);
ListD2 detailList2 = JSONUtils.toList(jsonArray2, detailClass2);
try
{
BeanUtils.setProperty(mainEntity, detailName1, detailList1);
BeanUtils.setProperty(mainEntity, detailName2, detailList2);
}
catch (Exception ex)
{
throw new RuntimeException("主從關(guān)系JSON反序列化實(shí)體失敗!");
}
return mainEntity;
}
/***
* 將JSON文本反序列化為主從關(guān)系的實(shí)體
* @param T泛型T 代表主實(shí)體類型
* @param D1泛型D1 代表從實(shí)體類型
* @param D2泛型D2 代表從實(shí)體類型
* @param jsonString JSON文本
* @param mainClass 主實(shí)體類型
* @param detailName1 從實(shí)體類在主實(shí)體類中的屬性
* @param detailClass1 從實(shí)體類型
* @param detailName2 從實(shí)體類在主實(shí)體類中的屬性
* @param detailClass2 從實(shí)體類型
* @param detailName3 從實(shí)體類在主實(shí)體類中的屬性
* @param detailClass3 從實(shí)體類型
* @return
*/
public static T, D1, D2, D3 T toBean(String jsonString,
ClassT mainClass, String detailName1, ClassD1 detailClass1,
String detailName2, ClassD2 detailClass2, String detailName3,
ClassD3 detailClass3)
{
JSONObject jsonObject = JSONObject.fromObject(jsonString);
JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1);
JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2);
JSONArray jsonArray3 = (JSONArray) jsonObject.get(detailName3);
T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
ListD1 detailList1 = JSONUtils.toList(jsonArray1, detailClass1);
ListD2 detailList2 = JSONUtils.toList(jsonArray2, detailClass2);
ListD3 detailList3 = JSONUtils.toList(jsonArray3, detailClass3);
try
{
BeanUtils.setProperty(mainEntity, detailName1, detailList1);
BeanUtils.setProperty(mainEntity, detailName2, detailList2);
BeanUtils.setProperty(mainEntity, detailName3, detailList3);
}
catch (Exception ex)
{
throw new RuntimeException("主從關(guān)系JSON反序列化實(shí)體失??!");
}
return mainEntity;
}
/***
* 將JSON文本反序列化為主從關(guān)系的實(shí)體
* @param T 主實(shí)體類型
* @param jsonString JSON文本
* @param mainClass 主實(shí)體類型
* @param detailClass 存放了多個(gè)從實(shí)體在主實(shí)體中屬性名稱和類型
* @return
*/
public static T T toBean(String jsonString, ClassT mainClass,
HashMapString, Class detailClass)
{
JSONObject jsonObject = JSONObject.fromObject(jsonString);
T mainEntity = JSONUtils.toBean(jsonObject, mainClass);
for (Object key : detailClass.keySet())
{
try
{
Class value = (Class) detailClass.get(key);
BeanUtils.setProperty(mainEntity, key.toString(), value);
}
catch (Exception ex)
{
throw new RuntimeException("主從關(guān)系JSON反序列化實(shí)體失敗!");
}
}
return mainEntity;
}
/**
* 封裝json數(shù)據(jù)從后臺(tái)傳輸
* @param obj
*/
public static void outPutJson(Object obj){
ActionContext context = ActionContext.getContext();
HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);
try {
response.getWriter().print(obj);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//測(cè)試類
String s1 = "[{id:1, pId:0, name:\"test1\" , open:true}]";
String s2 = "{id:2, pId:1, name:\"test211\" , open:true}";
String s3 = "{id:3, pId:2, name:\"test311\" , open:true}";
String s4 = "{id:4, pId:1, name:\"test411\" , open:true}";
ListString listZtree = new ArrayListString();
listZtree.add(s1);
listZtree.add(s2);
listZtree.add(s3);
listZtree.add(s4);
System.out.println(JSONUtils.toJSONString(listZtree));
}