如何用java递归生成带children的json串 java如何给有层级关系的JSON字符串做递归处理
\u5982\u4f55\u7528java\u9012\u5f52\u751f\u6210\u5e26children\u7684json\u4e32\u554a\uff1f\u6570\u636e\u96c6\u5df2\u7ecf\u6709\u4e86\u5728\u4e0b\u9762\u3002\u4e0d\u6e05\u695a\u4f60\u7684\u4e1a\u52a1\u9700\u6c42\u3002
1\u3001\u6570\u636e\u5b58\u653e\u5728xml\u6587\u4ef6\u4e2d\uff0c\u8bfb\u53d6xml\u6587\u4ef6
2\u3001json\u683c\u5f0f\uff0c\u5982\u679c\u4f60\u7684\u6570\u636e\u6709\u89c4\u5f8b\u53ef\u5faa\uff0c\u53ef\u4ee5\u7528\u4ee3\u7801\u5faa\u73af\u904d\u5386
3\u3001\u5982\u679c\u6570\u636e\u6765\u81ea\u6570\u636e\u5e93\uff0c\u90a3\u4e48\u4f7f\u7528sql\uff0c\u4e00\u822c\u7684\u6570\u636e\u5e93\u90fd\u63d0\u4f9b\u67e5\u8be2\u201c\u6811\u201d\u7684sql
\u5148\u9012\u5f52\u51fa\u4e00\u4e2a node\u5bf9\u8c61\uff0c\u518d\u5c06node\u5bf9\u8c61\u8f6c\u6362\u6210json\u4e32\u3002\u76f4\u63a5\u8fdb\u884c\u5b57\u7b26\u4e32\u7684json\u64cd\u4f5c\u4e0d\u5efa\u8bae\u3002
class Node{
private String id;
private String parentId;
private List children;
public void addChildren(Node child){
getChildren().add(child);
}
public List getChildren();
public String transformTojson(Node node ,StringBuffer jsonStr){
//\u9012\u5f52
if(jsonStr ==null){
StringBuffer jsonStr=new ();
}
if(node.id!=null){
//\u62fc\u63a5\u7236\u8282\u70b9json\u4e32
jsonStr.append(id:node.id,children:#&children);
}
List childNodeList = node.getChildren();
StringBuffer childrenSB = new();
for( Node node :childNodeList){
childrenSB=transformTojson(node);
}
sonStr.replaceFirst("#&children",childrenSB);
return jsonStr;
}
}
\u4f2a\u4ee3\u7801\u5927\u6982\u8fd9\u6837\u3002
transformTojson\u65b9\u6cd5\u53ef\u4ee5\u4e0d\u81ea\u5df1\u5199\uff0c\u76f4\u63a5\u4f7f\u7528\u7b2c\u4e09\u65b9\u5de5\u5177jar\u5305\u7684json\u8f6c\u5316\u65b9\u6cd5\uff0c\u6bd4\u5982gjson\u3002
先递归出一个 node对象,再将node对象转换成json串。直接进行字符串的json操作不建议。
class Node{
private String id;
private String parentId;
private List<Node> children;
public void addChildren(Node child){
getChildren().add(child);
}
public List<Node> getChildren();
public String transformTojson(Node node ,StringBuffer jsonStr){
//递归
if(jsonStr ==null){
StringBuffer jsonStr=new ();
}
if(node.id!=null){
//拼接父节点json串
jsonStr.append(id:node.id,children:#&children);
}
List childNodeList = node.getChildren();
StringBuffer childrenSB = new();
for( Node node :childNodeList){
childrenSB=transformTojson(node);
}
sonStr.replaceFirst("#&children",childrenSB);
return jsonStr;
}
}
伪代码大概这样。
transformTojson方法可以不自己写,直接使用第三方工具jar包的json转化方法,比如gjson。
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
/**
* 简单封装Jackson,实现JSON String<->Java Object的Mapper.
*
* 封装不同的输出风格, 使用不同的builder函数创建实例.
*
*/
public class JsonMapper {
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
private ObjectMapper mapper;
public JsonMapper() {
this(null);
}
public JsonMapper(Include include) {
mapper = new ObjectMapper();
// 设置输出时包含属性的风格
if (include != null) {
mapper.setSerializationInclusion(include);
}
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
public static JsonMapper alwaysMapper() {
return new JsonMapper(Include.ALWAYS);
}
public static JsonMapper nonNullMapper() {
return new JsonMapper(Include.NON_NULL);
}
/**
* 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
*/
public static JsonMapper nonEmptyMapper() {
return new JsonMapper(Include.NON_EMPTY);
}
/**
* 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
*/
public static JsonMapper nonDefaultMapper() {
return new JsonMapper(Include.NON_DEFAULT);
}
/**
* Object可以是POJO,也可以是Collection或数组。 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]".
*/
public String toJson(Object object) {
try {
return mapper.writeValueAsString(object);
}
catch (IOException e) {
logger.warn("write to json string error:" + object, e);
return null;
}
}
/**
* 反序列化POJO或简单Collection如List<String>.
*
* 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
*
* 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String, JavaType)
*
* @see #fromJson(String, JavaType)
*/
public <T> T fromJson(String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return mapper.readValue(jsonString, clazz);
}
catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 反序列化复杂Collection如List<Bean>,
* 先使用createCollectionType()或contructMapType()构造类型, 然后调用本函数.
*
* @see #createCollectionType(Class, Class...)
*/
public <T> T fromJson(String jsonString, JavaType javaType) {
if (StringUtils.isEmpty(jsonString)) {
return null;
}
try {
return (T) mapper.readValue(jsonString, javaType);
}
catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 构造Collection类型.
*/
public JavaType contructCollectionType(Class<? extends Collection> collectionClass, Class<?> elementClass) {
return mapper.getTypeFactory().constructCollectionType(collectionClass, elementClass);
}
/**
* 构造Map类型.
*/
public JavaType contructMapType(Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) {
return mapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
}
/**
* 当JSON里只含有Bean的部分属性时,更新一个已存在Bean,只覆盖该部分的属性.
*/
public void update(String jsonString, Object object) {
try {
mapper.readerForUpdating(object).readValue(jsonString);
}
catch (JsonProcessingException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
}
catch (IOException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
}
}
/**
* 输出JSONP格式数据.
*/
public String toJsonP(String functionName, Object object) {
return toJson(new JSONPObject(functionName, object));
}
/**
* 设定是否使用Enum的toString函数来读写Enum, 为False时时使用Enum的name()函数来读写Enum, 默认为False.
* 注意本函数一定要在Mapper创建後, 所有的读写动作之前调用.
*/
public void enableEnumUseToString() {
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
}
/**
* 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
* 默认会先查找jaxb的annotation,如果找不到再找jackson的。
*/
public void enableJaxbAnnotation() {
JaxbAnnotationModule module = new JaxbAnnotationModule();
mapper.registerModule(module);
}
/**
* 取出Mapper做进一步的设置或使用其他序列化API.
*/
public ObjectMapper getMapper() {
return mapper;
}
}
代码很简单就两个类一个TreeNode.java 和一个测试类Test.java(可直接运行)
在运行之前需要以下公共类:
commons-beanutils.jar
commons-collections.jar
commons-lang.jar
commons-logging.jar
ezmorph-1.0.6.jar
json-lib-2.3-jdk15.jar
package com.test;
import java.util.ArrayList;
public class TreeNode {
private String id;
private String pid;
private String name;
private String remark;
private ArrayList<TreeNode> children = new ArrayList<TreeNode>();
public TreeNode(String id, String pid, String name, String remark) {
this.id = id;
this.pid = pid;
this.name = name;
this.remark = remark;
}
public void add(TreeNode node) {//递归添加节点
if ("0".equals(node.pid)) {
this.children.add(node);
} else if (node.pid.equals(this.id)) {
this.children.add(node);
} else {
for (TreeNode tmp_node : children) {
tmp_node.add(node);
}
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public ArrayList<TreeNode> getChildren() {
return children;
}
public void setChildren(ArrayList<TreeNode> children) {
this.children = children;
}
}
测试类Test.java
package com.test;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
public static void main(String[] args) {
TreeNode root = new TreeNode("0", "0", "000000", "00JJJ");
TreeNode node = null;
node = new TreeNode("1", "0", "111111", "11AAA");
root.add(node);
node = new TreeNode("2", "0", "222222", "11BBB");
root.add(node);
node = new TreeNode("3", "2", "333333", "11CCC");
root.add(node);
// JSONObject obj = JSONObject.fromObject(root);//有根
JSONArray obj = JSONArray.fromObject(root.getChildren());// 不要根
System.out.println(obj.toString());
}
}
你自己 看看 就可以写了
package com.bochy.common.utils;
/*
*
* 转换JSON帮助�??
*
* */
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class JsonUtils {
public static String stringToJson(String s) {
if (s == null) {
return nullToJson();
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
switch (ch) {
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
if (ch >= '\u0000' && ch <= '\u001F') {
String ss = Integer.toHexString(ch);
sb.append("\\u");
for (int k = 0; k < 4 - ss.length(); k++) {
sb.append('0');
}
sb.append(ss.toUpperCase());
} else {
sb.append(ch);
}
}
}
return sb.toString();
}
public static String nullToJson() {
return "";
}
public static String objectToJson(Object obj) {
StringBuilder json = new StringBuilder();
if (obj == null) {
json.append("\"\"");
} else if (obj instanceof Number) {
json.append(numberToJson((Number) obj));
} else if (obj instanceof Boolean) {
json.append(booleanToJson((Boolean) obj));
} else if (obj instanceof String) {
json.append("\"").append(stringToJson(obj.toString())).append("\"");
} else if (obj instanceof Object[]) {
json.append(arrayToJson((Object[]) obj));
} else if (obj instanceof List) {
json.append(listToJson((List<?>) obj));
} else if (obj instanceof Map) {
json.append(mapToJson((Map<?, ?>) obj));
} else if (obj instanceof Set) {
json.append(setToJson((Set<?>) obj));
} else {
json.append(beanToJson(obj));
}
return json.toString();
}
public static String numberToJson(Number number) {
return number.toString();
}
public static String booleanToJson(Boolean bool) {
return bool.toString();
}
/** *//**
* @param bean
* bean对象
* @return String
*/
public static String beanToJson(Object bean) {
StringBuilder json = new StringBuilder();
json.append("{");
PropertyDescriptor[] props = null;
try {
props = Introspector.getBeanInfo(bean.getClass(), Object.class)
.getPropertyDescriptors();
} catch (IntrospectionException e) {
}
if (props != null) {
for (int i = 0; i < props.length; i++) {
try {
String name = objectToJson(props[i].getName());
String value = objectToJson(props[i].getReadMethod()
.invoke(bean));
json.append(name);
json.append(":");
json.append(value);
json.append(",");
} catch (Exception e) {
}
}
json.setCharAt(json.length() - 1, '}');
} else {
json.append("}");
}
return json.toString();
}
/** *//**
* @param list
* list对象
* @return String
*/
public static String listToJson(List<?> list) {
StringBuilder json = new StringBuilder();
json.append("[");
if (list != null && list.size() > 0) {
for (Object obj : list) {
json.append(objectToJson(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}
/** *//**
* @param array
* 对象数组
* @return String
*/
public static String arrayToJson(Object[] array) {
StringBuilder json = new StringBuilder();
json.append("[");
if (array != null && array.length > 0) {
for (Object obj : array) {
json.append(objectToJson(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}
/** *//**
* @param map
* map对象
* @return String
*/
public static String mapToJson(Map<?, ?> map) {
StringBuilder json = new StringBuilder();
json.append("{");
if (map != null && map.size() > 0) {
for (Object key : map.keySet()) {
json.append(objectToJson(key));
json.append(":");
json.append(objectToJson(map.get(key)));
json.append(",");
}
json.setCharAt(json.length() - 1, '}');
} else {
json.append("}");
}
return json.toString();
}
/** *//**
* @param set
* 集合对象
* @return String
*/
public static String setToJson(Set<?> set) {
StringBuilder json = new StringBuilder();
json.append("[");
if (set != null && set.size() > 0) {
for (Object obj : set) {
json.append(objectToJson(obj));
json.append(",");
}
json.setCharAt(json.length() - 1, ']');
} else {
json.append("]");
}
return json.toString();
}
}
绛旓細濡傛灉闈炶鑷繁鍘诲啓鐨勮瘽锛屽氨闇瑕佺敤鍒板弽灏勪簡銆傜畝鍗曟潵璇达紝灏辨槸鑾峰彇瀵硅薄鐨勬墍鏈夊睘鎬с傚鏉傝鐨勮瘽锛岃鍒ゆ柇瀵硅薄鐨勫睘鎬э紝鍒ゆ柇灞炴х被鍨嬶紝鍒ゆ柇灞炴у兼槸鍚︿负null锛屽垽鏂璞℃槸鍚︽槸鏈塼ransient淇グ锛屽垽鏂瓧绗︿覆閲岄潰鏄惁鏈夊弻寮曞彿绛夌瓑銆傜劧鍚庨氳繃StringBuffer鎴栨槸StringBuilder鍘绘嫾鎺ュ瓧绗︿覆锛屾潵鐢熸垚json涓诧紝鑷充簬鏄疭tringBuffer杩樻槸...
绛旓細1銆佹暟鎹瓨鏀惧湪xml鏂囦欢涓紝璇诲彇xml鏂囦欢 2銆乯son鏍煎紡锛屽鏋滀綘鐨勬暟鎹湁瑙勫緥鍙惊锛屽彲浠ョ敤浠g爜寰幆閬嶅巻 3銆佸鏋滄暟鎹潵鑷暟鎹簱锛岄偅涔堜娇鐢╯ql锛屼竴鑸殑鏁版嵁搴撻兘鎻愪緵鏌ヨ鈥滄爲鈥濈殑sql
绛旓細銆愮瓟妗堛戯細杩欐槸涓涓帓鍒楃殑渚嬪瓙锛屽畠鎵鍋氱殑宸ヤ綔鏄皢杈撳叆鐨勪竴涓瓧绗︿覆涓殑鎵鏈夊厓绱犺繘琛屾帓搴忓苟杈撳嚭锛屼緥濡傦細浣犵粰鍑虹殑鍙傛暟鏄漚bc鈥 鍒欑▼搴忎細杈撳嚭锛 abc acb bac bca cab cba a.绠楁硶鐨勫嚭鍙e湪浜庯細low=high涔熷氨鏄幇鍦ㄧ粰鍑虹殑鎺掑垪鍏冪礌鍙湁涓涓椂銆 b.绠楁硶鐨勯艰繎杩囩▼锛氬厛纭畾鎺掑垪鐨勭涓浣嶅厓绱狅紝涔熷氨鏄惊鐜...
绛旓細鍦↗ava缂栫▼涓紝閫掑綊绠楁硶鏄竴绉嶅父瑙佺殑瑙e喅闂鐨勬柟娉曘備緥濡傦紝鎴戜滑鍙互閫氳繃閫掑綊瀹炵幇姹夎濉旈棶棰橈紝璇ラ棶棰樻秹鍙婂皢涓涓鐨勭洏瀛愭寜鐗瑰畾椤哄簭浠庝竴涓煴瀛愮Щ鍔ㄥ埌鍙︿竴涓煴瀛愩備唬鐮佸畾涔変簡浠庢簮(A)鍒扮洰鏍(C)鐨勯掑綊绉诲姩鍑芥暟锛屽綋鍙湁1涓洏瀛愭椂锛岀洿鎺ョЩ鍔紱鍚﹀垯锛屽厛绉诲姩灏忕洏瀛愶紝鍐嶅皢澶х洏瀛愮Щ鑷充腑闂达紝鏈鍚庡皢灏忕洏瀛愮Щ鍥炵洰鏍囥
绛旓細1銆侀噰鐢ㄨ嚜椤跺悜涓婄殑閫掑綊鏂规硶锛屼唬鐮佸涓嬶細import java.util.Scanner;public class Test {@SuppressWarnings("resource")public static void main(String[] args) {// 浠庢帶鍒跺彴杈撳叆涓涓暣鏁癝canner in = new Scanner(System.in);int b = in.nextInt();// 澹版槑涓涓猅est瀵硅薄锛岃皟鐢╟al鏂规硶鑾峰緱缁撴灉Test ...
绛旓細濡傛灉鏄痟ibernate jsonlib鏈変釜config閰嶇疆涓涓嬪氨OK JsonConfig jsonConfig = new JsonConfig();jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);jsonConfig.setExcludes(new String[] { "handler","hibernateLazyInitializer" });jsonConfig.registerJsonValueProcessor(java.util.Date.clas...
绛旓細1銆閫掑綊鍋氫负涓绉嶇畻娉曞湪绋嬪簭璁捐璇█涓箍娉涗娇鐢紝鏄寚鍑芥暟/杩囩▼/瀛愮▼搴忓湪杩愯杩囩▼涓洿鎺ユ垨闂存帴璋冪敤鑷韩鑰浜х敓鐨勯噸鍏ョ幇璞°2銆侀掑綊绠楁硶涓鑸敤浜庤В鍐充笁绫婚棶棰橈細1锛夋暟鎹殑瀹氫箟鏄寜閫掑綊瀹氫箟鐨勩傦紙Fibonacci锛堟枑娉㈤偅濂戯級鐨勫嚱鏁帮級2锛夐棶棰樿В娉曟寜閫掑綊绠楁硶瀹炵幇銆傦紙鍥炴函锛3锛夋暟鎹殑缁撴瀯褰㈠紡鏄寜閫掑綊瀹氫箟鐨勩傦紙鏍戠殑閬嶅巻...
绛旓細//杈撳嚭閲戝瓧濉攊mportjava.util.Scanner;publicclassa1{publicstaticvoidmain(String[]args){Scannera=newScanner(System.in);intN=5;//瀹氫箟琛屾暟鐨勫彉閲廱ooleanb=true;do{try{System.out.println("璇疯緭鍏ユ暣鏁扮被鍨嬬殑鏁板瓧锛");N=a.nextInt();//鑾峰彇杈撳叆琛屾暟b=false;}catch(Exceptionea){a=newScanner(...
绛旓細瀹屾暣浠g爜(閫掑綊灏辨槸鍦ㄦ柟娉曢噷璋冪敤鑷韩鑰屽凡锛屾病浠涔堢█濂囩殑)public class DayMain { private String[] strArray;public String[] getStrArray() { return strArray;} public void setStrArray(String[] strArray) { this.strArray = strArray;} public void findIndexCycle() throws IOException{ System...
绛旓細閫掑綊缁撴潫 if(n<10){ return isMark(n); } //妯¢櫎涓涓暟锛屾眰浣欙紝浣跨敤浣欐暟鍒ゆ柇鏄惁涓庢寚瀹氭暟鍖归厤 return isMark(n % 10) + countEm(n / 10); } public int isMark(int source){ //濡傛灉浣欐暟涓巑ark鐩哥瓑锛屽垯杩斿洖1锛屽惁鍒欒繑鍥0 if(source == MARK){ return...