18 June 2017

Google Gson API: Convert JSON String To ArrayList - Java

Json String to ArrayList
Java Json 2017
package com.gson.json;

import java.lang.reflect.Type;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class JsonStringToList {

    public static void main(String a[]) {

        // Json String
        String str = "[{'empId':1200},{'name': 'Antonio'},{'designation': 'Manager'},{'department': 'Account'},{'salary': 25000}]";

        Gson gsonObj = new Gson();

        // import java.lang.reflect.Type;
        Type type = new TypeToken<List<Employee>>() {}.getType();
        List<Employee> list = gsonObj.fromJson(str, type);

        System.out.println(list);

    }
}

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;
    }
}

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang