学无先后,达者为师

网站首页 编程语言 正文

com.fasterxml.jackson.databind.ObjectMapper

作者:spencer_tseng 更新时间: 2023-12-07 编程语言

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>
    <groupId>com.fasterxml.jackson.core</groupId>
    <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 = "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<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();
		}
	}

}

原文链接:https://blog.csdn.net/spencer_tseng/article/details/134656783

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新