从Json到POJO的GSON获取空字段

时间:2015-07-06 23:53:44

标签: java json gson pojo

我正在使用Google.GSON库将JSON文件反序列化为名为Account的POJO。 我查看过这里的大部分文章,但是我从.fromJson得到的POJO对象有空字段。

这是我的代码:

import java.io.*;
import java.util.*;
import com.google.gson.*;
import com.google.gson.stream.JsonReader;

public class lastTest {

    public static void main(String[] args) throws IOException {

        ArrayList<Account> Customers = new ArrayList<Account>();
        try {
                JsonReader jRead = new JsonReader(new FileReader("myJson3.json"));

         //   InputStreamReader jRead = new InputStreamReader(new FileInputStream("myJson3.json"));

                Account a = new Gson().fromJson(jRead, Account.class);
                Customers.add(a);

                System.out.println(Customers.toString());

        }
        catch (FileNotFoundException e) {
            System.out.print("File not found!");
        }
    }
}

帐户类如下所示:

public class Account
{
    private String name;
    private String number;
    private String address1;
    private String city;
    private String state;
    private String zip;

    public String getZip (){
        return zip; }

    public void setZip (String zip){
        this.zip = zip; }

    public String getName (){
        return name; }

    public void setName (String name){
        this.name = name; }

    public String getState (){
        return state; }

    public void setState (String state){
        this.state = state; }

    public String getAddress1 (){
        return address1; }

    public void setAddress1 (String address1){
        this.address1 = address1; }

    public String getNumber (){
        return number; }

    public void setNumber (String number){
        this.number = number; }

    public String getCity () {
        return city; }

    public void setCity (String city){
        this.city = city; }

@Override
    public String toString()
    {
        return "zip = "+zip+", name = "+name+", state = "+state+", address1 = "+address1+", number = "+number+", city = "+city;
    }
}

我的JSON文件如下所示:

{
    "1": {
        "account": {
            "address1": "1234 Golf Drive", 
            "city": "Santa Clara", 
            "name": "John Smith", 
            "number": "123445577", 
            "state": "CA", 
            "zip": "95050"
        }, 
        "comparison": {
            "data": [
                .
                .
                .
            ], 
            "buffer": "true"
        },  
        "month": "5", 
        "locale": "en_us", 
        "period": "April 30, 2014 - May 31, 2015",
        "service": {
            "address": "1234 Golf Drive", 
            "city": "Santa Clara", 
            "name": "John Smith", 
            "state": "CA", 
            "zip": "95050"
        }
    }
}

当我尝试打印我的POJO的实例变量时,它们都是空的。

输出我得到:

[zip = null, name = null, state = null, address1 = null, number = null, city = null]

0 个答案:

没有答案