package zwf;

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

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.8.7

<dependency&gt;
    <groupId&gt;com.fasterxml.jackson.core</groupId&gt;
    <artifactId>jackson-databind</artifactId>
    <version>2.8.7</version>
</dependency>
 *
 * @author ZengWenFeng
 * @date 2023.11.27
 * @email 117791303@qq.com
 * @mobile 13805029595
 */

public class Test2Json
{

	public Test2Json()
	{
		
	}

	public static void main(String[] args)
	{
		// 包含制表符的文本数据
		String tabSeparatedData = "nametagetcitynJohnt25tNew YorknAlicet30tChicago";

		// 将制表符文本数据转换为JSON
		String[] lines = tabSeparatedData.split("n");
		String[] headers = lines[0].split("t");

		// 创建一个ObjectMapper对象
		ObjectMapper objectMapper = new ObjectMapper();

		// 创建一个空的JSON数组
		List<Object> jsonArray = new ArrayList<Object>();

		// 遍历文本数据的每一行,将其转换为JSON对象
		for (int i = 1; i < lines.length; i++)
		{
			String[] values = lines[i].split("t");
			Map<String, String> jsonMap = new HashMap<String, String>();

			// 遍历每个字段,将其添加到JSON对象中
			for (int j = 0; j < headers.length; j++)
			{
				jsonMap.put(headers[j], values[j]);
			}

			// 将JSON对象添加到JSON数组jsonArray.add(jsonMap);
		}

		// 将JSON数组转换为JSON字符串
		try
		{
			String jsonOutput = objectMapper.writeValueAsString(jsonArray);
			System.out.println(jsonOutput);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注