com.fasterxml.jackson.databind.ObjectMapper

com.fasterxml.jackson.databind.ObjectMapper_第1张图片

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


    com.fasterxml.jackson.core
    jackson-databind
    2.8.7

 *
 * @author ZengWenFeng
 * @date 2023.11.27
 * @email [email protected]
 * @mobile 13805029595
 */

public class Test2Json
{

	public Test2Json()
	{
		
	}

	public static void main(String[] args)
	{
		// 包含制表符的文本数据
		String tabSeparatedData = "name\tage\tcity\nJohn\t25\tNew York\nAlice\t30\tChicago";

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

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

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

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

			// 遍历每个字段,将其添加到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();
		}
	}

}
 
  

你可能感兴趣的:(java,java)