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();
}
}
}
com.fasterxml.jackson.databind.ObjectMapper
最新推荐文章于 2024-04-10 08:28:43 发布