在Java中将文本文件转换为JSON [英] Convert text file to JSON in Java
本文介绍了在Java中将文本文件转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将文本文件转换为Json文件? 我有一个原始的in.txt文件,如下所示:
How do I convert a text file to Json file? I have a raw in.txt file as below:
{"person":{"name":"AAAA","sid":09328,"location":"Sao Paulo"}}
{"person":{"name":"BBBBB","sid":01934,"location":"Brasilia"}}
非常感谢您的帮助!
推荐答案
要在JSON中转换文本文件,可以在代码中使用JACKSON OBJECT MAPPER jar.
To convert text file in JSON you can use JACKSON OBJECT MAPPER jar in your code.
创建一个简单的Employee pojo.我们将从文件中读取JSON字符串,并将其映射到Employee类.
Create a simple Employee pojo. We will read JSON string from a file and map it to Employee class.
这是代码:
public class Employee {
private int empId;
private String name;
private String designation;
private String department;
private int salary;
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("************************************");
sb.append("\nempId: ").append(empId);
sb.append("\nname: ").append(name);
sb.append("\ndesignation: ").append(designation);
sb.append("\ndepartment: ").append(department);
sb.append("\nsalary: ").append(salary);
sb.append("\n************************************");
return sb.toString();
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
本次POJO课后 最后是将JSON字符串值转换为Java对象的示例
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
import com.java2novice.json.models.Employee;
public class JsonToObject {
public static void main(String a[]){
ObjectMapper mapper = new ObjectMapper();
try {
File jsonInputFile = new File("C:\\jsonInput.txt");
Employee emp = mapper.readValue(jsonInputFile, Employee.class);
System.out.println(emp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是您的JSON文件: jsonInput.txt文件包含以下json输入:
AND here Is your JSON file: jsonInput.txt file contains below json input:
{
"empId": 1017,
"name": "Nagesh Y",
"designation": "Manager",
"department": "Java2Novice",
"salary": 30000
}
希望这会对您有所帮助.
Hope this will help you.
这篇关于在Java中将文本文件转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文