如何在Java中将JSON字符串转换为JSON对象(Gson)?

时间:2018-04-23 22:26:24

标签: java json rest spring-boot

我正在使用外部API,响应主体是JSON格式的String。我正在使用Gson将String解析为JSON对象。但是,尝试在浏览器中显示对象时出现以下错误。

  

SyntaxError:JSON.parse:第1行第1列的意外字符   JSON数据

这是我的代码:

控制器

    @RequestMapping("/player")
public JsonArray displayPlayer() throws Exception{


    String player = "PacSnackz";

    smite.createSession();

    String test = smite.getPlayer(player);

    JsonArray playerObj = new JsonParser().parse(test).getAsJsonArray();

    return playerObj;

}

Smite Class

      public String getPlayer(String player) throws Exception {
        if (!isSessionValid() && !createSession()) return "session null";
        return getURL(combine(new String[] {
                baseURL + "getplayer" + responseFormat,
                devID,
                getSignature("getplayer"),
                sessionID,
                getTimestamp(),
                player
        }, "/"));
}

这就是JSON String的样子:

JSON字符串

[{"Avatar_URL":"","Created_Datetime":"8\/16\/2016 4:30:14 AM","Id":9993055,"Last_Login_Datetime":"4\/23\/2018 8:47:56 PM","Leaves":3,"Level":17,"Losses":19,"MasteryLevel":1,"Name":"PacSnackz","Personal_Status_Message":"","Rank_Stat_Conquest":0,"Rank_Stat_Duel":0,"Rank_Stat_Joust":0,"RankedConquest":{"Leaves":0,"Losses":0,"Name":"League","Points":0,"PrevRank":0,"Rank":0,"Rank_Stat_Conquest":null,"Rank_Stat_Duel":null,"Rank_Stat_Joust":null,"Season":0,"Tier":0,"Trend":0,"Wins":0,"player_id":null,"ret_msg":null},"RankedDuel":{"Leaves":0,"Losses":0,"Name":"Duel","Points":0,"PrevRank":0,"Rank":0,"Rank_Stat_Conquest":null,"Rank_Stat_Duel":null,"Rank_Stat_Joust":null,"Season":0,"Tier":0,"Trend":0,"Wins":0,"player_id":null,"ret_msg":null},"RankedJoust":{"Leaves":0,"Losses":0,"Name":"Joust","Points":0,"PrevRank":0,"Rank":0,"Rank_Stat_Conquest":null,"Rank_Stat_Duel":null,"Rank_Stat_Joust":null,"Season":0,"Tier":0,"Trend":0,"Wins":0,"player_id":null,"ret_msg":null},"Region":"North America","TeamId":0,"Team_Name":"","Tier_Conquest":0,"Tier_Duel":0,"Tier_Joust":0,"Total_Achievements":28,"Total_Worshippers":510,"Wins":35,"ret_msg":null}]

我正在使用Spring Boot Java和Google的Gson库。我也没看过杰克逊。

1 个答案:

答案 0 :(得分:0)

我想出了答案。诀窍是将Player设置为数组。对于其他对象,我使用了for循环来返回多个对象。对于此示例,它设置为0,因为只有一个播放器。

@RequestMapping("/player")
public Player displayPlayer() throws Exception{


    String player = "PacSnackz";

    smite.createSession();

    String test = smite.getPlayer(player);

    Gson gson = new Gson();

    Player[] playerObj = gson.fromJson(test, Player[].class);

    return playerObj[0];



}