18 June 2017

Google Gson API: Convert JSON String file To Object - Java

Json String To Object
Java Json 2017
package com.gson.json;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

import com.google.gson.Gson;

public class JsonStringToObject {

    public static void main(String a[]) {

        BufferedReader br = null;
        Gson gsonObj = new Gson();
        try {
            br = new BufferedReader(new FileReader("C:\\Users\\Lonely-Cat\\workspace\\Demo01\\src\\com\\gson\\json\\jsonInput.json"));
            // convert json string to object
            Employee emp = gsonObj.fromJson(br, Employee.class);
            System.out.println("Emp Name: " + emp.getName());
            System.out.println("Emp Id: " + emp.getEmpId());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

class Employee {

    private int empId;
    private String name;
    private String designation;
    private String department;
    private int salary;

    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;
    }
}
{
 "empId": 1002,
 "name": "Antonio",
 "designation": "Manager",
 "department": "Accounts",
 "salary": 60000
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang