代码如下
目前成都创新互联公司已为上千余家的企业提供了网站建设、域名、网站空间、网站运营、企业网站设计、麻城网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class JsonValidator {
private CharacterIterator it;
private char c;
private int col;
public JsonValidator(){
}
/**
* 验证一个字符串是否是合法的JSON串
*
* @param input 要验证的字符串
* @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来操作json对象和json数组,具体用法如下
1:java对象与json串转换:
java对象—json串:
JSONObject JSONStr = JSONObject.fromObject(object);
String str = JSONStr.toString();
json串—java对象:
JSONObject jsonObject = JSONObject.fromObject( jsonString );
Object pojo = JSONObject.toBean(jsonObject,pojoCalss);
2:java数组对象与json串转换:
java数组—json串:
JSONArray arrayStr = JSONArray.fromObject(List?);
String str = arrayStr.toString();
json串—java数组:
JSONArray array = JSONArray.fromObject(str);
List? list = JSONArray.toList(array, ?.class);
java中将数据封装为JSON包,可以使用java提供的jsonArray这个工具类进行转换,代码如下:
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对象序列化为JSON文本
*/
public static T String toJSONString(ListT list)
{
JSONArray jsonArray = JSONArray.fromObject(list);
return jsonArray.toString();
}
/***
* 将对象序列化为JSON文本
* @param object
* @return
*/
public static String toJSONString(Object object)
{
JSONArray jsonArray = JSONArray.fromObject(object);
return jsonArray.toString();
}
/***
* 将JSON对象数组序列化为JSON文本
* @param jsonArray
* @return
*/
public static String toJSONString(JSONArray jsonArray)
{
return jsonArray.toString();
}
/***
* 将JSON对象序列化为JSON文本
* @param jsonObject
* @return
*/
public static String toJSONString(JSONObject jsonObject)
{
return jsonObject.toString();
}
/***
* 将对象转换为List对象
* @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;
}
/***
* 将对象转换为Collection对象
* @param object
* @return
*/
public static Collection toCollection(Object object)
{
JSONArray jsonArray = JSONArray.fromObject(object);
return JSONArray.toCollection(jsonArray);
}
/***
* 将对象转换为JSON对象数组
* @param object
* @return
*/
public static JSONArray toJSONArray(Object object)
{
return JSONArray.fromObject(object);
}
/***
* 将对象转换为JSON对象
* @param object
* @return
*/
public static JSONObject toJSONObject(Object object)
{
return JSONObject.fromObject(object);
}
/***
* 将对象转换为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;
}
/***
* 将对象转换为ListMapString,Object
* @param object
* @return
*/
// 返回非实体类型(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对象数组转换为传入类型的List
* @param T
* @param jsonArray
* @param objectClass
* @return
*/
public static T ListT toList(JSONArray jsonArray, ClassT objectClass)
{
return JSONArray.toList(jsonArray, objectClass);
}
/***
* 将对象转换为传入类型的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对象转换为传入类型的对象
* @param T
* @param jsonObject
* @param beanClass
* @return
*/
public static T T toBean(JSONObject jsonObject, ClassT beanClass)
{
return (T) JSONObject.toBean(jsonObject, beanClass);
}
/***
* 将将对象转换为传入类型的对象
* @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文本反序列化为主从关系的实体
* @param T 泛型T 代表主实体类型
* @param D 泛型D 代表从实体类型
* @param jsonString JSON文本
* @param mainClass 主实体类型
* @param detailName 从实体类在主实体类中的属性名称
* @param detailClass 从实体类型
* @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("主从关系JSON反序列化实体失败!");
}
return mainEntity;
}
/***
* 将JSON文本反序列化为主从关系的实体
* @param T泛型T 代表主实体类型
* @param D1泛型D1 代表从实体类型
* @param D2泛型D2 代表从实体类型
* @param jsonString JSON文本
* @param mainClass 主实体类型
* @param detailName1 从实体类在主实体类中的属性
* @param detailClass1 从实体类型
* @param detailName2 从实体类在主实体类中的属性
* @param detailClass2 从实体类型
* @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("主从关系JSON反序列化实体失败!");
}
return mainEntity;
}
/***
* 将JSON文本反序列化为主从关系的实体
* @param T泛型T 代表主实体类型
* @param D1泛型D1 代表从实体类型
* @param D2泛型D2 代表从实体类型
* @param jsonString JSON文本
* @param mainClass 主实体类型
* @param detailName1 从实体类在主实体类中的属性
* @param detailClass1 从实体类型
* @param detailName2 从实体类在主实体类中的属性
* @param detailClass2 从实体类型
* @param detailName3 从实体类在主实体类中的属性
* @param detailClass3 从实体类型
* @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("主从关系JSON反序列化实体失败!");
}
return mainEntity;
}
/***
* 将JSON文本反序列化为主从关系的实体
* @param T 主实体类型
* @param jsonString JSON文本
* @param mainClass 主实体类型
* @param detailClass 存放了多个从实体在主实体中属性名称和类型
* @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("主从关系JSON反序列化实体失败!");
}
}
return mainEntity;
}
/**
* 封装json数据从后台传输
* @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();
}
}
}
//测试类
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));
}
售后响应及时
7×24小时客服热线数据备份
更安全、更高效、更稳定价格公道精准
项目经理精准报价不弄虚作假合作无风险
重合同讲信誉,无效全额退款