I am consuming an external API to which the response body is a String in JSON format. I am using Gson
to parse the String into a JSON Object. However, I get the following error when trying to display the object in browser.
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Here is my code:
Controller
@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
}, "/"));
}
This is what the JSON String looks like:
JSON String
[{"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}]
I am using Spring Boot Java and Google's Gson library. I have looked into Jackson as well with no luck either.
I figured out the answer. The trick was to set Player to an array. For other objects I had I used a for loop to return multiple objects. For this example it is set to 0 since there is only one player.
@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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.