如何访问json中的数组?

时间:2019-04-03 19:51:09

标签: java arrays json gson

使用gson,您将如何访问此json中的aguelTable数组中的值?

这是json结构,并存储为一个名为“ dataRead”的字符串

{
   "data":{
      "fixtures":[
         {
         }
      ],
    "leagueTable":[
         {
         }
      ]
   }
}

我的gson代码如下所示,并且打印行将访问数组中的对象

Data data = new Gson().fromJson(dataRead, Data.class);
System.out.println(data.leagueTable[0].team);

我的数据类看起来像这样,并且与json中的内容匹配

public class Data {
    LeagueTable[] leagueTable;

    public Data(LeagueTable[] leagueTable) {
        this.leagueTable = leagueTable;
    }

    public static class LeagueTable {
        String team;
        int played, gamesWon, gamesDraw, gameLost, goalsFor, goalsAgainst, goalsDifference, points;

        public LeagueTable(String team, int played, int gamesWon, int gamesDraw, int gameLost, int goalsFor,
                int goalsAgainst, int goalsDifference, int points) {
            this.team = team;
            this.played = played;
            this.gamesWon = gamesWon;
            this.gamesDraw = gamesDraw;
            this.gameLost = gameLost;
            this.goalsFor = goalsFor;
            this.goalsAgainst = goalsAgainst;
            this.goalsDifference = goalsDifference;
            this.points = points;
        }

    }
}

我期望LeagueTable数组中第一支球队的一线,但我得到以下消息:

Exception in thread "main" java.lang.NullPointerException

1 个答案:

答案 0 :(得分:0)

您用Data表示的数据结构不适合您的json结构。因此,Gson仅创建类型为Data的新实例,而不用成员的值填充它。

试试这个实现:

public class MyObject {

    private Data data;

    public static class Data {

       private FixturesStrutue[] fixtures;
       private LeagueTable[] leagueTable;

       public static class LeagueTable {
           String team;
           int played, gamesWon, gamesDraw, gameLost, goalsFor, goalsAgainst, 
                   goalsDifference, points;

       }

       public static class FixturesStrutue {
           String member1;
           int member2;

       }
   }
}

现在,使用Gson:

Data data = new Gson().fromJson(dataRead, MyObject.class);
System.out.println(data.leagueTable[0].team);

最后一行(data.leagueTable[0].team)仍将引发NPE,因为json的leagueTable数组中没有元素。添加至少一个元素就可以了。

Gson会将json中的所有属性注入到名称类中的相应成员。如果希望成员和属性使用不同的名称,请阅读有关SerializedName的信息。