2017-10-05 2 views
0

classe JSON:gson.fromJson Expected BEGIN_OBJECT mais était BEGIN_ARRAY

package json; 

public class RankAPI { 
    private String hotStreak; 
    private String leagueName; 
    private String tier; 
    private String freshBlood; 
    private String playerOrTeamId; 
    private String leaguePoints; 
    private String inactive; 
    private String rank; 
    private String veteran; 
    private String queueType; 
    private String losses; 
    private String playerOrTeamName; 
    private String wins; 

public String getHotStreak() 
{ 
    return hotStreak; 
} 

public void setHotStreak (String hotStreak) 
{ 
    this.hotStreak = hotStreak; 
} 

public String getLeagueName() 
{ 
    return leagueName; 
} 

public void setLeagueName (String leagueName) 
{ 
    this.leagueName = leagueName; 
} 

public String getTier() 
{ 
    return tier; 
} 

public void setTier (String tier) 
{ 
    this.tier = tier; 
} 

public String getFreshBlood() 
{ 
    return freshBlood; 
} 

public void setFreshBlood (String freshBlood) 
{ 
    this.freshBlood = freshBlood; 
} 

public String getPlayerOrTeamId() 
{ 
    return playerOrTeamId; 
} 

public void setPlayerOrTeamId (String playerOrTeamId) 
{ 
    this.playerOrTeamId = playerOrTeamId; 
} 

public String getLeaguePoints() 
{ 
    return leaguePoints; 
} 

public void setLeaguePoints (String leaguePoints) 
{ 
    this.leaguePoints = leaguePoints; 
} 

public String getInactive() 
{ 
    return inactive; 
} 

public void setInactive (String inactive) 
{ 
    this.inactive = inactive; 
} 

public String getRank() 
{ 
    return rank; 
} 

public void setRank (String rank) 
{ 
    this.rank = rank; 
} 

public String getVeteran() 
{ 
    return veteran; 
} 

public void setVeteran (String veteran) 
{ 
    this.veteran = veteran; 
} 

public String getQueueType() 
{ 
    return queueType; 
} 

public void setQueueType (String queueType) 
{ 
    this.queueType = queueType; 
} 

public String getLosses() 
{ 
    return losses; 
} 

public void setLosses (String losses) 
{ 
    this.losses = losses; 
} 

public String getPlayerOrTeamName() 
{ 
    return playerOrTeamName; 
} 

public void setPlayerOrTeamName (String playerOrTeamName) 
{ 
    this.playerOrTeamName = playerOrTeamName; 
} 

public String getWins() 
{ 
    return wins; 
} 

public void setWins (String wins) 
{ 
    this.wins = wins; 
} 

@Override 
public String toString() 
{ 
    return "ClassPojo [hotStreak = "+hotStreak+", leagueName = "+leagueName+", tier = "+tier+", freshBlood = "+freshBlood+", playerOrTeamId = "+playerOrTeamId+", leaguePoints = "+leaguePoints+", inactive = "+inactive+", rank = "+rank+", veteran = "+veteran+", queueType = "+queueType+", losses = "+losses+", playerOrTeamName = "+playerOrTeamName+", wins = "+wins+"]"; 
} 
} 

autre code:

package com.rhidlor.leaguetool; 

import json.SummonerAPI; 
import json.RankAPI; 
import com.google.gson.Gson; 
import com.google.gson.annotations.SerializedName; 
import java.io.IOException; 
import java.net.URL; 
import java.util.ResourceBundle; 
import javafx.event.ActionEvent; 
import javafx.fxml.FXML; 
import javafx.fxml.Initializable; 
import javafx.scene.control.Label; 
import javafx.scene.control.TextField; 
import okhttp3.OkHttpClient; 
import okhttp3.Request; 
import okhttp3.Response; 

public class FXMLController implements Initializable { 
    public static OkHttpClient client = new OkHttpClient(); 
    public static Gson gson = new Gson(); 
    public static SummonerAPI summonerAPI; 
    public static RankAPI rankAPI; 
    public static String summonerJSON = null; 
    public static String rankJSON = null; 
    public static String username; 
    public static String id; 
    public String key = "RGAPI-dd11b8d0-3178-4eb1-8dfa-0d5bf6fb1b24"; 
    //https://na1.api.riotgames.com 

@FXML private Label summonerLabel; 
@FXML private Label rankLabel; 
@FXML private Label winrateLabel; 
@FXML private TextField usernameTextField; 

@FXML 
private void handleButtonAction(ActionEvent event) { 
    username = usernameTextField.getText(); 
    try{ 
     summonerJSON = getJSON("https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/" + username + "?api_key=" + key); 
    }catch(Exception e) { 
      e.printStackTrace(); 
    } 
    summonerAPI = gson.fromJson(summonerJSON, SummonerAPI.class); 
    id = summonerAPI.getId(); 
    System.out.println("ID: " + id); 

    try{ 
     rankJSON = getJSON("https://na1.api.riotgames.com/lol/league/v3/positions/by-summoner/" + id + "?api_key=" + key); 
     System.out.println("This worked"); 
    }catch(Exception e) { 
     System.out.println("This failed"); 
     e.getCause().printStackTrace(); 
    } 
    rankAPI = gson.fromJson(rankJSON, RankAPI.class); 

    setValues(username); 
} 

public static String getJSON(String url) throws IOException { 
    Request request = new Request.Builder() 
    .url(url) 
    .build(); 

    Response response = client.newCall(request).execute(); 
    return response.body().string(); 
} 

public void setValues(String username){ 
    summonerLabel.setText(username + " Level: " + summonerAPI.getSummonerLevel()); 
    //System.out.println(rankAPI.getWins()); 
    //rankLabel.setText("Rank: " + rankAPI.getTier() + " " + rankAPI.getRank() + " LP: " + rankAPI.getLeaguePoints()); 
    //int winrate = (parseInt(rankAPI.getWins())/(parseInt(rankAPI.getWins()) + parseInt(rankAPI.getLosses()))) * 100; 
    //winrateLabel.setText("Winrate: " + winrate + "%"); 
} 

@Override 
public void initialize(URL url, ResourceBundle rb) { 
    // TODO 
}  

}

Cette ligne provoque l'erreur:

rankAPI = gson.fromJson(rankJSON, RankAPI.class); 

erreur : Causé par: java.lang.IllegalS tateException: BEGIN_OBJECT attendu, mais BEGIN_ARRAY à la ligne 1, colonne 2, chemin $

Si quelqu'un pouvait m'aider avec ceci, il serait grandement apprécié. La partie SummonerAPI de ce code fonctionne parfaitement et sa classe json est presque identique à la classe RankAPI json. Je comprends que certains hors du code peuvent ne pas avoir de sens ou sembler hors de propos, c'est parce que j'essayais de dépanner le code, mais clairement échoué.

+0

Il semble que le JSON que vous recevez du serveur est une liste d'objets (tableau), cela signifie que le JSON commence par « [ » , qui indique un tableau au lieu de '{' qui indique un objet. Donc soit votre serveur retourne quelque chose de mal, soit vous devriez vous attendre à une liste plutôt qu'à un objet. – Piwo

Répondre

1

On dirait que la chaîne JSON (rankJSON) est un tableau de documents JSON et non un seul document JSON.

Si vous consignez ce JSON, vous verrez qu'il commence par [ par exemple.

[ 
    { 
     ... 
    } 
] 

Vous essayez de désérialiser en un seul RankAPI, vous devriez plutôt désérialiser dans un List<RankAPI>, par exemple;

List<RankAPI> r = gson.fromJson(rankJSON, new TypeToken<ArrayList<RankAPI>>(){}.getType()); 

est ici un cas de test pour vérifier ce comportement:

@Test 
public void twoWayTransform() { 
    Gson gson = new GsonBuilder().serializeNulls().create(); 

    List<RankAPI> incomings = Arrays.asList(new RankAPI(), new RankAPI()); 

    String json = gson.toJson(incomings); 

    // use TypeToken to inform Gson about the type of the elements in the generic list 
    List<RankAPI> fromJson = gson.fromJson(json, new TypeToken<ArrayList<RankAPI>>(){}.getType()); 

    assertEquals(2, fromJson.size()); 
    for (RankAPI incoming : incomings) { 
     // this will pass if RankAPI has an equals() method 
     assertTrue(fromJson.contains(incoming)); 
    } 
} 
+0

Merci, je comprends parfaitement ce que mon problème était maintenant! –

+0

Je n'ai toujours pas mon code de travail, je sais ce que mon problème est maintenant et j'ai essayé le code que vous avez fourni mais il dit: types incompatibles: RankAPI ne peut pas être converti en liste . Toute aide supplémentaire serait grandement appréciée –

+0

Excuses, il y avait une faute de frappe dans ma réponse. Je l'ai mis à jour maintenant: 'Liste r = gson.fromJson (rankJSON, List.class);' – glytching