且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java中将文本文件转换为JSON

更新时间:2023-01-23 10:46:31

要在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.