java 通过 list<item> 实现 json 生成

Java JSON 数据拼接

 

java  实现 json 拼接

 

功能:通过 item 添加数据的方式 ,解析拼接成 json 字符串

 

待优化项: 使用 jsonobject.put(name,value) 而并非 map.put(name,value)

 

结果展示

 

[
{"gId":0,"id":1,"name":"config_latest_version","pId":0,"type":1,"value":"1.0.43"},
{"gId":0,"id":2,"name":"app_info","pId":0,"type":2},
{"gId":0,"id":3,"name":"app_latest_version","pId":2,"type":1,"value":"3.1.44"},
{"gId":0,"id":4,"name":"app_version_illustration","pId":2,"type":1,"value":"www.baoyou.com android版本3.1.44"},
{"gId":0,"id":5,"name":"country_code","pId":0,"type":3},
{"gId":1,"id":6,"name":"code","pId":5,"type":1,"value":"1"},
{"gId":1,"id":7,"name":"value","pId":5,"type":1,"value":"+86"},
{"gId":1,"id":8,"name":"sequence","pId":5,"type":1,"value":"1"},
{"gId":0,"id":9,"name":"slide_show_list","pId":0,"type":3},
{"gId":1,"id":10,"name":"type","pId":9,"type":1,"value":"slide_show_001"},
{"gId":1,"id":11,"name":"effective_start_time","pId":9,"type":1,"value":"2016-09-06 08:00:00"},
{"gId":1,"id":12,"name":"effective_end_time","pId":9,"type":1,"value":"2016-09-06 08:00:00"},
{"gId":1,"id":13,"name":"times","pId":9,"type":1,"value":"3"},
{"gId":1,"id":14,"name":"sequence","pId":9,"type":1,"value":"1"},
{"gId":1,"id":15,"name":"picture_list","pId":9,"type":3},
{"gId":1,"id":16,"name":"code","pId":15,"type":1,"value":"1"},
{"gId":1,"id":17,"name":"vale","pId":15,"type":1,"value":"https://www.baoyou.com/function_introduction/1.png?version=2016930"},
{"gId":1,"id":18,"name":"url","pId":15,"type":1,"value":""},
{"gId":1,"id":19,"name":"sequence","pId":15,"type":1,"value":"1"},
{"gId":2,"id":20,"name":"code","pId":15,"type":1,"value":"2"},
{"gId":2,"id":21,"name":"vale","pId":15,"type":1,"value":"https://www.baoyou.com/function_introduction/2.png?version=2016930"},
{"gId":2,"id":22,"name":"url","pId":15,"type":1,"value":""},
{"gId":2,"id":23,"name":"sequence","pId":15,"type":1,"value":"2"},
{"gId":3,"id":24,"name":"code","pId":15,"type":1,"value":"3"},
{"gId":3,"id":25,"name":"vale","pId":15,"type":1,"value":"https://www.baoyou.com/function_introduction/3.png?version=20161129"},
{"gId":3,"id":26,"name":"url","pId":15,"type":1,"value":""},
{"gId":3,"id":27,"name":"sequence","pId":15,"type":1,"value":"3"},
{"gId":2,"id":28,"name":"type","pId":9,"type":1,"value":"slide_show_002"},
{"gId":2,"id":29,"name":"effective_start_time","pId":9,"type":1,"value":"2016-09-06 08:00:00"},
{"gId":2,"id":30,"name":"effective_end_time","pId":9,"type":1,"value":"2016-09-06 08:00:00"},
{"gId":2,"id":31,"name":"times","pId":9,"type":1,"value":"3"},
{"gId":2,"id":32,"name":"sequence","pId":9,"type":1,"value":"2"},
{"gId":2,"id":33,"name":"picture_list","pId":9,"type":3},
{"gId":1,"id":34,"name":"code","pId":33,"type":1,"value":"1"},
{"gId":1,"id":35,"name":"vale","pId":33,"type":1,"value":"https://www.baoyou.com/function_introduction/1.png?version=2016930"},
{"gId":1,"id":36,"name":"url","pId":33,"type":1,"value":""},
{"gId":1,"id":37,"name":"sequence","pId":33,"type":1,"value":"1"},
{"gId":2,"id":38,"name":"code","pId":33,"type":1,"value":"2"},
{"gId":2,"id":39,"name":"vale","pId":33,"type":1,"value":"https://www.baoyou.com/function_introduction/2.png?version=2016930"},
{"gId":2,"id":40,"name":"url","pId":33,"type":1,"value":""},
{"gId":2,"id":41,"name":"sequence","pId":33,"type":1,"value":"2"}
]

 

 

{
    "app_info": {
        "app_latest_version": "3.1.44",
        "app_version_illustration": "www.baoyou.com android版本3.1.44"
    },
    "config_latest_version": "1.0.43",
    "country_code": [
        {
            "code": "1",
            "sequence": "1",
            "value": "+86"
        }
    ],
    "slide_show_list": [
        {
            "effective_end_time": "2016-09-06 08:00:00",
            "effective_start_time": "2016-09-06 08:00:00",
            "picture_list": [
                {
                    "code": "3",
                    "sequence": "3",
                    "url": "",
                    "vale": "https://www.baoyou.com/function_introduction/3.png?version=20161129"
                },
                {
                    "code": "2",
                    "sequence": "2",
                    "url": "",
                    "vale": "https://www.baoyou.com/function_introduction/2.png?version=2016930"
                },
                {
                    "code": "1",
                    "sequence": "1",
                    "url": "",
                    "vale": "https://www.baoyou.com/function_introduction/1.png?version=2016930"
                }
            ],
            "sequence": "1",
            "times": "3",
            "type": "slide_show_001"
        },
        {
            "effective_end_time": "2016-09-06 08:00:00",
            "effective_start_time": "2016-09-06 08:00:00",
            "picture_list": [
                {
                    "code": "2",
                    "sequence": "2",
                    "url": "",
                    "vale": "https://www.baoyou.com/function_introduction/2.png?version=2016930"
                },
                {
                    "code": "1",
                    "sequence": "1",
                    "url": "",
                    "vale": "https://www.baoyou.com/function_introduction/1.png?version=2016930"
                }
            ],
            "sequence": "2",
            "times": "3",
            "type": "slide_show_002"
        }
    ]
}

 

 代码部分:

 

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TreeNodeGId
{
 
}

 

 

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TreeNodeId
{
 
}

 

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import www.baoyou.com.annotation.TreeNodeGId;
import www.baoyou.com.annotation.TreeNodeId;
import www.baoyou.com.annotation.TreeNodeName;
import www.baoyou.com.annotation.TreeNodePId;
import www.baoyou.com.annotation.TreeNodeType;
import www.baoyou.com.annotation.TreeNodeValue;
import www.baoyou.com.util.node.BuildHelper;
import www.baoyou.com.util.node.JsonHelper;
public class Item {
/*
[
 { id:1, pId:0,gid:null,type:"1", name:"config_latest_version",  open:true,value:"1.0.43"},
 { id:2, pId:0,gid:null,type:"2", name:"app_info", open:true},
	 { id:3, pId:2,gid:null,type:"1", name:"app_latest_version",value:"3.1.44"},
	 { id:4, pId:2,gid:null,type:"1", name:"app_version_illustration",value:"www.baoyou.com android版本3.1.44"},
 { id:5, pId:0,gid:null,type:"3", name:"country_code"},
	 { id:6, pId:5,gid:1,type:"1", name:"code",value:"1"},
	 { id:7, pId:5,gid:1,type:"1", name:"value",value:"+86"},
	 { id:8, pId:5,gid:1,type:"1", name:"sequence",value:"1"}

{ id:9, pId:0,gid:0,type:"3", name:"slide_show_list"},
	{ id:10, pId:9,gid:1,type:"3", name:"type",value:"slide_show_001"},
	{ id:11, pId:9,gid:1,type:"3", name:"effective_start_time",value:"2016-09-06 08:00:00"},
	{ id:12, pId:9,gid:1,type:"3", name:"effective_end_time",value:"2016-12-06 08:00:00"},
	{ id:13, pId:9,gid:1,type:"3", name:"times",value:"3"},
	{ id:14, pId:9,gid:1,type:"3", name:"sequence",value:"1"},
	{ id:15, pId:9,gid:1,type:"3", name:"picture_list"},
		{ id:16, pId:15,gid:1,type:"3", name:"code",value:"1"},
		{ id:17, pId:15,gid:1,type:"3", name:"vale",value:"https://www.baoyou.com/1.png?version=2016930"},
		{ id:18, pId:15,gid:1,type:"3", name:"url",value:""},
		{ id:19, pId:15,gid:1,type:"3", name:"sequence",value:"1"},

		{ id:20, pId:15,gid:2,type:"3", name:"code",value:"2"},
		{ id:21, pId:15,gid:2,type:"3", name:"vale",value:"https://www.baoyou.com/2.png?version=2016930"},
		{ id:22, pId:15,gid:2,type:"3", name:"url",value:""},
		{ id:23, pId:15,gid:2,type:"3", name:"sequence",value:"2"},

		{ id:24, pId:15,gid:3,type:"3", name:"code",value:"3"},
		{ id:25, pId:15,gid:3,type:"3", name:"vale",value:"https://www.baoyou.com/3.png?version=20161129"},
		{ id:26, pId:15,gid:3,type:"3", name:"url",value:""},
		{ id:27, pId:15,gid:3,type:"3", name:"sequence",value:"3"}
	
	{ id:28, pId:9,gid:2,type:"3", name:"type",value:"slide_show_002"},
	{ id:29, pId:9,gid:2,type:"3", name:"effective_start_time",value:"2016-09-06 08:00:00"},
	{ id:30, pId:9,gid:2,type:"3", name:"effective_end_time",value:"2016-12-06 08:00:00"},
	{ id:31, pId:9,gid:2,type:"3", name:"times",value:"3"},
	{ id:32, pId:9,gid:2,type:"3", name:"sequence",value:"1"},
	{ id:33, pId:9,gid:2,type:"3", name:"picture_list"},
		{ id:34, pId:33,gid:1,type:"3", name:"code",value:"4"},
		{ id:35, pId:33,gid:1,type:"3", name:"vale",value:"https://www.baoyou.com/carouselfigure02.png?version=2016930"},
		{ id:36, pId:33,gid:1,type:"3", name:"url",value:""},
		{ id:37, pId:33,gid:1,type:"3", name:"sequence",value:"4"},

		{ id:38, pId:33,gid:2,type:"3", name:"code",value:"5"},
		{ id:39, pId:33,gid:2,type:"3", name:"vale",value:"https://www.baoyou.com/carouselfigure02.png?version=2016930"},
		{ id:40, pId:33,gid:2,type:"3", name:"url",value:""},
		{ id:41, pId:33,gid:2,type:"3", name:"sequence",value:"5"}

] 
	*/
	
   public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
		// Item(int id, int pId, int type, int gId, String name, String value) 
		Item item1 = new Item(1,0,1,0,"config_latest_version","1.0.43");	
		Item item2 = new Item(2,0,2,0,"app_info",null);
		Item item3 = new Item(3,2,1,0,"app_latest_version","3.1.44");
		Item item4 = new Item(4,2,1,0,"app_version_illustration","android版本3.1.44");		
		Item item5 = new Item(5,0,3,0,"country_code",null); 		
		
		Item item6 = new Item(6,5,1,1,"code","1");
		Item item7 = new Item(7,5,1,1,"value","+86");
		Item item8 = new Item(8,5,1,1,"sequence","1");		 
		
		Item item9 = new Item(9,5,1,2,"code","2");
		Item item10 = new Item(10,5,1,2,"value","+001");
		Item item11 = new Item(11,5,1,2,"sequence","2");	
		
		
		
		Map map = new TreeMap<String,String>();
		map.put(item1.name, item1.value);
		
		Map map2 = new TreeMap<String,String>();
		map2.put(item3.name, item3.value);
		map2.put(item4.name, item4.value);
		map.put(item2.name, map2);
		 
		Map map6 = new TreeMap<String,String>();
		map6.put(item6.name, item6.value);
		map6.put(item7.name, item7.value);
		map6.put(item8.name, item8.value); 
		List list = new ArrayList<Map>(); 
		list.add(map6);
		map.put(item5.name,list);
		
		 
		
		System.out.println(JSON.toJSONString(map2)); 
		System.out.println(JSON.toJSONString(map));
		
		
		
	  List <Item> original = Lists.newArrayList(item1,item2,item3,item4,item5,item6,item7,item8,item9,item10,item11);
	  List<Node> convertDatas2Nodes = BuildHelper.convertDatas2Nodes(original);  
	  List<Node> sortedNodes = BuildHelper.getSortedNodes(convertDatas2Nodes);
	  Map result = JsonHelper.getResult(sortedNodes);
 	  System.out.println(JSON.toJSONString(result,SerializerFeature.DisableCircularReferenceDetect));
	}

	@TreeNodeId
	public int id = 0;
	@TreeNodePId
	public int pId = 0;
	@TreeNodeType
	public int type = 1; // 1:k-v 2:k-o 3:k-l
	@TreeNodeGId
	public int gId = 0; // 3 存在 1 null 2 null
	@TreeNodeName
	public String name = null;
	@TreeNodeValue
	public String value = null; // 1 存在 2 null 3 null

	 
	
	
	public Item(int id, int pId, int type, int gId, String name, String value) {
		this.id = id;
		this.pId = pId;
		this.type = type;
		this.gId = gId;
		this.name = name;
		this.value = value;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getpId() {
		return pId;
	}

	public void setpId(int pId) {
		this.pId = pId;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public int getgId() {
		return gId;
	}

	public void setgId(int gId) {
		this.gId = gId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return "Item [name=" + name + ", value=" + value + "]";
	}
	
	
	
}

 

import java.util.ArrayList;
import java.util.List;

import www.baoyou.com.annotation.TreeNodeGId;
import www.baoyou.com.annotation.TreeNodeId;
import www.baoyou.com.annotation.TreeNodeName;
import www.baoyou.com.annotation.TreeNodePId;
import www.baoyou.com.annotation.TreeNodeType;
import www.baoyou.com.annotation.TreeNodeValue;
public class Node {

	@TreeNodeId
	public int id = 0;
	@TreeNodePId
	public int pId = 0;
	@TreeNodeType
	public int type = 1; // 1:k-v 2:k-o 3:k-l
	@TreeNodeGId
	public int gId = 0; // 3 存在 1 null 2 null
	@TreeNodeName
	public String name = null;
	@TreeNodeValue
	public String value = null; // 1 存在 2 null 3 null
	
	public int level;
	
	public boolean isLeaf;
	
	private Node parent;
	public List<Node> child= new ArrayList<Node>();

	
	public Node(){}
	
	public Node(int id, int pId, int type, int gId, String name, String value) {
		this.id = id;
		this.pId = pId;
		this.type = type;
		this.gId = gId;
		this.name = name;
		this.value = value;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getpId() {
		return pId;
	}

	public void setpId(int pId) {
		this.pId = pId;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public int getgId() {
		return gId;
	}

	public void setgId(int gId) {
		this.gId = gId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public int getLevel() {
		return parent == null ? 1 : parent.getLevel() + 1;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public boolean isLeaf() {
		return this.child.size() == 0;
	}

 

	public List<Node> getChild() {
		return child;
	}

	public void setChild(List<Node> child) {
		this.child = child;
	}

	public Node getParent() {
		return parent;
	}

	public void setParent(Node parent) {
		this.parent = parent;
	}
	
	
	public boolean isRoot(){
		
		
		return this.parent == null;
	}
	
	 
	
}

 

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import www.baoyou.com.annotation.TreeNodeGId;
import www.baoyou.com.annotation.TreeNodeId;
import www.baoyou.com.annotation.TreeNodeName;
import www.baoyou.com.annotation.TreeNodePId;
import www.baoyou.com.annotation.TreeNodeType;
import www.baoyou.com.annotation.TreeNodeValue;
import www.baoyou.com.entity.Item;
import www.baoyou.com.entity.Node;
public class BuildHelper {

	 
	@SuppressWarnings("rawtypes")
	public static <T> List<Node> convertDatas2Nodes(List<T> datas)
			throws IllegalArgumentException, IllegalAccessException
	{
		List<Node> nodes = new ArrayList<Node>();
		Node node = null;
		for (T t : datas)
		{
		     int id = 0; 
			 int pId = 0; 
			 int type = 1; // 1:k-v 2:k-o 3:k-l 
			 int gId = 0; // 3 存在 1 null 2 null 
			 String name = null; 
			 String value= null;

			node = new Node();
			Class clazz = t.getClass();
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields)
			{
				if (field.getAnnotation(TreeNodeId.class) != null)
				{
					field.setAccessible(true);
					id = field.getInt(t);
				}
				if (field.getAnnotation(TreeNodePId.class) != null)
				{
					field.setAccessible(true);
					pId = field.getInt(t);
				}
				if (field.getAnnotation(TreeNodeType.class) != null)
				{
					field.setAccessible(true);
					type = field.getInt(t);
				}
				if (field.getAnnotation(TreeNodeGId.class) != null)
				{
					field.setAccessible(true);
					gId = field.getInt(t);
				}
				if (field.getAnnotation(TreeNodeName.class) != null)
				{
					field.setAccessible(true);
					name = (String) field.get(t);
				}
				if (field.getAnnotation(TreeNodeValue.class) != null)
				{
					field.setAccessible(true);
					value = (String) field.get(t);
				}
				
			}
			node = new Node(id, pId, type, gId, name, value);
			nodes.add(node);
		} 
		for (int i = 0; i < nodes.size(); i++)
		{
			Node n = nodes.get(i);

			for (int j = i + 1; j < nodes.size(); j++)
			{
				Node m = nodes.get(j);

				if (m.getpId() == n.getId())
				{
					n.getChild().add(m);
					m.setParent(n);
				} else if (m.getId() == n.getpId())
				{
					m.getChild().add(n);
					n.setParent(m);
				}
			}
		}
		//System.out.println(JSON.toJSONString(nodes,SerializerFeature.DisableCircularReferenceDetect) );
		return nodes;
	}
	
	public static <T> List<Node> getSortedNodes(List<T> datas) throws IllegalArgumentException,
			IllegalAccessException
	{
		List<Node> nodes = convertDatas2Nodes(datas); 
		return getRootNodes(nodes);
	}

	 
	private static List<Node> getRootNodes(List<Node> nodes)
	{
		List<Node> root = new ArrayList<Node>();
		for (Node node : nodes)
		{
			if (node.isRoot())
			{
				root.add(node);
			}
		}
		return root;
	}
	
	
	/*
	[
	 { id:1, pId:0,gid:null,type:"1", name:"config_latest_version",  open:true,value:"1.0.43"},
	 { id:2, pId:0,gid:null,type:"2", name:"app_info", open:true},
		 { id:3, pId:2,gid:null,type:"1", name:"app_latest_version",value:"3.1.44"},
		 { id:4, pId:2,gid:null,type:"1", name:"app_version_illustration",value:"www.baoyou.com android版本3.1.44"},
	 { id:5, pId:0,gid:null,type:"3", name:"country_code"},
		 { id:6, pId:5,gid:1,type:"1", name:"code",value:"1"},
		 { id:7, pId:5,gid:1,type:"1", name:"value",value:"+86"},
		 { id:8, pId:5,gid:1,type:"1", name:"sequence",value:"1"}

	{ id:9, pId:0,gid:0,type:"3", name:"slide_show_list"},
		{ id:10, pId:9,gid:1,type:"1", name:"type",value:"slide_show_001"},
		{ id:11, pId:9,gid:1,type:"1", name:"effective_start_time",value:"2016-09-06 08:00:00"},
		{ id:12, pId:9,gid:1,type:"1", name:"effective_end_time",value:"2016-12-06 08:00:00"},
		{ id:13, pId:9,gid:1,type:"1", name:"times",value:"3"},
		{ id:14, pId:9,gid:1,type:"1", name:"sequence",value:"1"},
		{ id:15, pId:9,gid:1,type:"3", name:"picture_list"},
			{ id:16, pId:15,gid:1,type:"3", name:"code",value:"1"},
			{ id:17, pId:15,gid:1,type:"3", name:"vale",value:"https://www.baoyou.com/function_introduction/1.png?version=2016930"},
			{ id:18, pId:15,gid:1,type:"3", name:"url",value:""},
			{ id:19, pId:15,gid:1,type:"3", name:"sequence",value:"1"},

			{ id:20, pId:15,gid:2,type:"3", name:"code",value:"2"},
			{ id:21, pId:15,gid:2,type:"3", name:"vale",value:"https://www.baoyou.com/function_introduction/2.png?version=2016930"},
			{ id:22, pId:15,gid:2,type:"3", name:"url",value:""},
			{ id:23, pId:15,gid:2,type:"3", name:"sequence",value:"2"},

			{ id:24, pId:15,gid:3,type:"3", name:"code",value:"3"},
			{ id:25, pId:15,gid:3,type:"3", name:"vale",value:"https://www.baoyou.com/function_introduction/3.png?version=20161129"},
			{ id:26, pId:15,gid:3,type:"3", name:"url",value:""},
			{ id:27, pId:15,gid:3,type:"3", name:"sequence",value:"3"}
		
		{ id:28, pId:9,gid:2,type:"3", name:"type",value:"slide_show_002"},
		{ id:29, pId:9,gid:2,type:"3", name:"effective_start_time",value:"2016-09-06 08:00:00"},
		{ id:30, pId:9,gid:2,type:"3", name:"effective_end_time",value:"2016-12-06 08:00:00"},
		{ id:31, pId:9,gid:2,type:"3", name:"times",value:"3"},
		{ id:32, pId:9,gid:2,type:"3", name:"sequence",value:"1"},
		{ id:33, pId:9,gid:2,type:"3", name:"picture_list"},
			{ id:34, pId:33,gid:1,type:"3", name:"code",value:"4"},
			{ id:35, pId:33,gid:1,type:"3", name:"vale",value:"https://www.baoyou.com/function_introduction/carouselfigure02.png?version=2016930"},
			{ id:36, pId:33,gid:1,type:"3", name:"url",value:""},
			{ id:37, pId:33,gid:1,type:"3", name:"sequence",value:"4"},

			{ id:38, pId:33,gid:2,type:"3", name:"code",value:"5"},
			{ id:39, pId:33,gid:2,type:"3", name:"vale",value:"https://www.baoyou.com/function_introduction/carouselfigure02.png?version=2016930"},
			{ id:40, pId:33,gid:2,type:"3", name:"url",value:""},
			{ id:41, pId:33,gid:2,type:"3", name:"sequence",value:"5"}

	] 
		*/
	
	@SuppressWarnings({ "unused", "rawtypes" })
	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
		
		Item item1 = new Item(1,0,1,0,"config_latest_version","1.0.43");	
		Item item2 = new Item(2,0,2,0,"app_info",null);
		Item item3 = new Item(3,2,1,0,"app_latest_version","3.1.44");
		Item item4 = new Item(4,2,1,0,"app_version_illustration","www.baoyou.com android版本3.1.44");		
		Item item5 = new Item(5,0,3,0,"country_code",null); 		
		Item item6 = new Item(6,5,1,1,"code","1");
		Item item7 = new Item(7,5,1,1,"value","+86");
		Item item8 = new Item(8,5,1,1,"sequence","1");		 
		
		Item item9 = new Item(9,0,3,0,"slide_show_list",null);		 
		
		Item item10 = new Item(10,9,1,1,"type","slide_show_001");		
		Item item11 = new Item(11,9,1,1,"effective_start_time","2016-09-06 08:00:00");		
		Item item12 = new Item(12,9,1,1,"effective_end_time","2016-09-06 08:00:00");		
		Item item13 = new Item(13,9,1,1,"times","3");		
		Item item14 = new Item(14,9,1,1,"sequence","1");		
		Item item15 = new Item(15,9,3,1,"picture_list",null);		
		
		Item item16 = new Item(16,15,1,1,"code","1");
		Item item17 = new Item(17,15,1,1,"vale","https://www.baoyou.com/function_introduction/1.png?version=2016930");
		Item item18 = new Item(18,15,1,1,"url","");
		Item item19 = new Item(19,15,1,1,"sequence","1");
		
		Item item20 = new Item(20,15,1,2,"code","2");
		Item item21 = new Item(21,15,1,2,"vale","https://www.baoyou.com/function_introduction/2.png?version=2016930");
		Item item22 = new Item(22,15,1,2,"url","");
		Item item23 = new Item(23,15,1,2,"sequence","2");
		
		Item item24 = new Item(24,15,1,3,"code","3");
		Item item25 = new Item(25,15,1,3,"vale","https://www.baoyou.com/function_introduction/3.png?version=20161129");
		Item item26 = new Item(26,15,1,3,"url","");
		Item item27 = new Item(27,15,1,3,"sequence","3");
	
		 
		Item item28 = new Item(28,9,1,2,"type","slide_show_002");		
		Item item29 = new Item(29,9,1,2,"effective_start_time","2016-09-06 08:00:00");		
		Item item30 = new Item(30,9,1,2,"effective_end_time","2016-09-06 08:00:00");		
		Item item31 = new Item(31,9,1,2,"times","3");		
		Item item32 = new Item(32,9,1,2,"sequence","2");		
		Item item33 = new Item(33,9,3,2,"picture_list",null);		
		
		Item item34 = new Item(34,33,1,1,"code","1");
		Item item35 = new Item(35,33,1,1,"vale","https://www.baoyou.com/function_introduction/1.png?version=2016930");
		Item item36 = new Item(36,33,1,1,"url","");
		Item item37 = new Item(37,33,1,1,"sequence","1");
		
		Item item38 = new Item(38,33,1,2,"code","2");
		Item item39 = new Item(39,33,1,2,"vale","https://www.baoyou.com/function_introduction/2.png?version=2016930");
		Item item40 = new Item(40,33,1,2,"url","");
		Item item41 = new Item(41,33,1,2,"sequence","2");
		 
	    List <Item> list = Lists.newArrayList(item1,item2,item3,item4,item5,item6,item7,item8,item9,item10
	    		                              ,item11,item12,item13,item14,item15,item16,item17,item18,item19,item20
	    		                              ,item21,item22,item23,item24,item25,item26,item27
	    		                               ,item28,item29,item30
	    		                              ,item31,item32,item33,item34,item35,item36,item37,item38,item39,item40
	    		                              ,item41  
	    		);
		
	    List<Node> nodes = convertDatas2Nodes(list);
	    
	    List<Node> sortedNodes = getSortedNodes(nodes);
	    System.out.println(JSON.toJSONString(sortedNodes) );
	    
	    Map mapresult = new TreeMap<String,String>();
		Map result = JsonHelper.getResult(sortedNodes);
		System.out.println(JSON.toJSONString(result));
	    
		   
	}
}

 

 

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import www.baoyou.com.entity.Node;
public class JsonHelper {

	
 @SuppressWarnings({ "rawtypes" })
public static Map getResult2(List<Node> list){ 
	 return getResult(list);
 }
 
 @SuppressWarnings({ "rawtypes", "unchecked" })
public static List getResult3(List<Node> list){  
	 List root = new ArrayList<Map>();  
	 Map<String,List> ll = new HashMap<String,List>();
	 for (Node n :list) {
		List llist = ll.get(n.pId +"@"+n.gId);
		if(llist == null){
			llist = new ArrayList<Node>();
		}
		llist.add(n);
		ll.put(n.pId +"@"+n.gId,llist);
	 }
	 for (List<Node> lnode : ll.values()) {
		 root.add(getResult(lnode));
	 }
	 return root;
 }
 
  @SuppressWarnings({ "rawtypes", "unchecked" })
public static Map getResult(List<Node> list){
	  Map map = new TreeMap();
	  for (Node n : list) {
		switch (n.type) {
		case 1:
			map.put(n.name, n.value);
			break;
        case 2: 
			map.put(n.name,getResult2(n.child));
			break;
        case 3: 
		    map.put(n.name,getResult3(n.child));
			break;
		default:
			break;
		}
	  }
	  
	  return map;
  }
  
  
 
  
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者 

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。

 

个人主页http://knight-black-bob.iteye.com/



 
 
 谢谢您的赞助,我会做的更好!

<think>首先,用户的问题是:"我想将Java中的List<String>转换为String 请问Java convert List of String to String"。所以,我需要提供一个清晰的解决方案,如何在Java中将一个List<String>转换为一个String。 关键点是:输入是List<String>,输出是String。例如,列表["apple", "orange", "banana"]应该转换为字符串"apple, orange, banana"或类似格式。 在Java中,有几种方法可以实现这个: 1. 使用String.join()方法(Java 8及以上):这是最简单的方式。String.join()接受一个分隔符和一个Iterable(如List),并返回一个字符串。 ```java List<String> list = Arrays.asList("apple", "orange", "banana"); String result = String.join(", ", list); System.out.println(result); // 输出: apple, orange, banana ``` 2. 使用StringBuilder:手动遍历列表并追加元素。 ```java List<String> list = Arrays.asList("apple", "orange", "banana"); StringBuilder sb = new StringBuilder(); for (String s : list) { if (sb.length() > 0) { sb.append(", "); } sb.append(s); } String result = sb.toString(); ``` 3. 使用Stream API(Java 8及以上):使用Collectors.joining()。 ```java List<String> list = Arrays.asList("apple", "orange", "banana"); String result = list.stream().collect(Collectors.joining(", ")); ``` 4. 使用Apache Commons Lang库:如果项目中使用了这个库,可以使用StringUtils.join()。 ```java import org.apache.commons.lang3.StringUtils; List<String> list = Arrays.asList("apple", "orange", "banana"); String result = StringUtils.join(list, ", "); ``` 但最推荐的是使用Java内置的String.join(),因为它简洁高效。 现在,关于系统级指令: - 所有行内数学表达式必须使用$...$格式,但这个问题是关于Java编程的,没有数学表达式,所以可能不需要。 - 独立公式必须使用$$...$$格式并单独成段:同样,这里没有公式。 - LaTeX语法正确:不适用。 - 使用中文回答:是的,整个回答需要用中文。 - 生成相关问题:在回答结束后,添加相关问题部分。 - 回答中引用的段落末尾自然地添加引用标识:用户提供了几个引用,我需要参考它们。 用户提供的引用: - [^1]: 关于R语言的paste()函数,但用户的问题是关于Java的,所以可能不直接相关。 - [^2]: 错误信息:Failed to convert value of type 'java.lang.String' to required type 'java.util.List',这是关于将String转换为List的失败,而用户是想将List转换为String,所以是相反的操作。可能用户遇到了错误,但问题明确是List到String。 - [^3]: 类似错误,关于String到Integer的转换失败。 - [^4]: 另一个关于String到List转换失败的例子。 这些引用似乎不直接相关,因为用户的问题是关于List到String的转换,而引用是关于String到List或其他类型的转换失败。我应该在回答中专注于解决用户的问题,并可能提及避免常见错误。 用户说:"上述引用仅供参考,并不是用户真正的需求",所以我应该基于用户的问题来回答。 回答结构: - 清晰,逐步解决问题。 - 尽量保证真实可靠。 回答内容: 1. 介绍问题:解释如何将List<String>转换为String。 2. 提供几种方法,推荐最简单的方法。 3. 给出代码示例。 4. 解释注意事项,比如空列表或null处理。 5. 结束时生成相关问题。 相关问题建议: 1. 如何处理列表中的空值或null元素? 2. 如何自定义分隔符? 3. 如果列表很大,性能如何? 4. 其他语言中类似转换的例子? 用中文回答。 大纲: - 开头:直接回答问题。 - 方法1:使用String.join() - 方法2:使用StringBuilder - 方法3:使用Stream API - 方法4:使用第三方库(可选) - 总结推荐方法 - 相关问题</think>### Java中将List<String>转换为String的方法 在Java中,将`List<String>`转换为`String`是一个常见需求,通常用于将列表元素连接成一个字符串,并添加分隔符(如逗号、空格等)。以下我将逐步介绍几种高效且可靠的方法,包括核心语法、代码示例和注意事项。所有方法均基于Java标准库(Java 8及以上),无需第三方依赖。 #### 1. **使用`String.join()`方法(推荐)** - **原理**:`String.join()`是Java 8引入的静态方法,直接接受分隔符和`Iterable`(如`List`),高效连接所有元素。 - **代码示例**: ```java import java.util.Arrays; import java.util.List; public class ListToStringExample { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "orange", "banana"); // 使用逗号和空格作为分隔符 String result = String.join(", ", list); System.out.println(result); // 输出: apple, orange, banana } } ``` - **优点**:简洁高效,代码可读性强。 - **注意事项**: - 如果列表为`null`,会抛出`NullPointerException`。建议提前检查:`if (list != null)`。 - 空列表会返回空字符串`""`。 - 分隔符可自定义,例如`String.join(" | ", list)`输出`apple | orange | banana`。 #### 2. **使用`StringBuilder`手动拼接** - **原理**:遍历列表,使用`StringBuilder`逐个追加元素和分隔符。适合Java 8以下版本或需要精细控制的情况。 - **代码示例**: ```java import java.util.Arrays; import java.util.List; public class ListToStringExample { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "orange", "banana"); StringBuilder sb = new StringBuilder(); for (String item : list) { if (sb.length() > 0) { sb.append(", "); // 添加分隔符 } sb.append(item); } String result = sb.toString(); System.out.println(result); // 输出: apple, orange, banana } } ``` - **优点**:兼容性好(支持Java 5+),可处理复杂逻辑(如跳过空值)。 - **注意事项**: - 性能优于字符串直接拼接(`+`运算符),尤其在大型列表上。 - 如果列表包含`null`元素,会追加`"null"`字符串。需添加空值检查:`if (item != null) sb.append(item)`。 #### 3. **使用Stream API(Java 8+)** - **原理**:通过Stream的`Collectors.joining()`收集器连接元素,支持更灵活的链式操作。 - **代码示例**: ```java import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ListToStringExample { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "orange", "banana"); String result = list.stream() .collect(Collectors.joining(", ")); System.out.println(result); // 输出: apple, orange, banana } } ``` - **优点**:易于扩展,例如过滤空值:`.filter(item -> item != null).collect(Collectors.joining(", "))`。 - **注意事项**: - 并行流(`parallelStream()`)可能提升大列表性能,但需测试线程安全。 - 如果列表为空,返回空字符串。 #### 4. **使用第三方库(如Apache Commons Lang)** - **原理**:库如Apache Commons Lang提供`StringUtils.join()`,简化操作,但需额外依赖。 - **代码示例**: ```java import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.List; public class ListToStringExample { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "orange", "banana"); String result = StringUtils.join(list, ", "); System.out.println(result); // 输出: apple, orange, banana } } ``` - **优点**:代码更简洁,内置空值处理(忽略`null`元素)。 - **注意事项**:需添加Maven依赖: ```xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency> ``` #### 总结与推荐 - **最佳实践**:优先使用`String.join()`(Java 8+),因为它简洁高效。若需兼容旧版本,用`StringBuilder`。 - **常见错误避免**: - **空指针问题**:始终检查列表是否为`null`,例如: ```java String result = (list == null || list.isEmpty()) ? "" : String.join(", ", list); ``` - **类型转换错误**:确保输入是`List<String>`而非其他类型。如果遇到类似`Failed to convert value of type 'java.lang.String' to required type 'java.util.List'`的错误[^2][^4],通常是因为尝试将字符串直接当作列表使用,而非本问题中的转换方向。 - **分隔符选择**:根据需求调整分隔符,例如JSON格式可用`String.join("\", \"", list)`。 如果您的列表数据来自外部接口(如第三方API),确保输入类型正确,避免类型不匹配的异常[^4]。 ### 相关问题 1. 如何在Java中处理List中的null元素,避免转换后出现"null"字符串? 2. 如果分隔符是动态的(如根据元素内容变化),如何实现List到String的转换? 3. 在大型数据集下,哪种转换方法性能最优? 4. 如何将转换后的String再转回List<String>?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值