如何根据指定key从champion.json中获取对应id并适配Android列表
Hey there! Let's work through your League of Legends champion data lookup and image loading issue. I’ll break this down into two key parts: fixing the JSON data node reading, and using the champion key to load images in your MatchListAdapter.
Fixing the JSON Data Node Reading in loadJSONFromAsset
First, let's recap the structure of the champion.json file: the top-level object has a data field, which contains a map where each key is a champion's ID (like Aatrox) and the value is an object with that champion's details—including the numeric key you're using (like 266).
The most common issue with reading the data node is forgetting to explicitly fetch it from the root JSON object. Here's a corrected version of your loadJSONFromAsset method that properly accesses the data node:
import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; public JSONObject loadJSONFromAsset(Context context) { String jsonContent = null; try { // Open the champion.json file from assets InputStream inputStream = context.getAssets().open("champion.json"); int fileSize = inputStream.available(); byte[] buffer = new byte[fileSize]; inputStream.read(buffer); inputStream.close(); // Convert buffer to string and parse into JSON jsonContent = new String(buffer, StandardCharsets.UTF_8); JSONObject rootJson = new JSONObject(jsonContent); // Return the "data" node directly—this is where champion mappings live return rootJson.getJSONObject("data"); } catch (IOException | org.json.JSONException e) { e.printStackTrace(); return null; } }
Next, create a reusable map to link champion keys to their IDs. This avoids parsing the JSON every time you need a lookup. Initialize this map in your Activity, Application class, or a dedicated utility class:
import java.util.HashMap; import java.util.Iterator; import java.util.Map; // Initialize a global map to hold key -> champion ID mappings private Map<String, String> championKeyToIdMap = new HashMap<>(); // Populate the map after loading the JSON private void populateChampionMap(Context context) { JSONObject championData = loadJSONFromAsset(context); if (championData == null) return; try { Iterator<String> championIds = championData.keys(); while (championIds.hasNext()) { String championId = championIds.next(); JSONObject championDetails = championData.getJSONObject(championId); String championKey = championDetails.getString("key"); // Map the numeric key to the champion ID championKeyToIdMap.put(championKey, championId); } } catch (org.json.JSONException e) { e.printStackTrace(); } }
Don't forget to call populateChampionMap(context) when your app starts (like in onCreate of your main Activity).
Using Champion Key to Load Images in MatchListAdapter
Now that we have our lookup map, we can use it in MatchListAdapter to get the champion ID from the key, then load the image with Picasso.
First, pass the map to the adapter via its constructor:
public class MatchListAdapter extends RecyclerView.Adapter<MatchListAdapter.ViewHolder> { private List<YourMatchItem> matchItems; private Map<String, String> championKeyToIdMap; private Context context; // Adapter constructor public MatchListAdapter(Context context, List<YourMatchItem> matchItems, Map<String, String> championKeyToIdMap) { this.context = context; this.matchItems = matchItems; this.championKeyToIdMap = championKeyToIdMap; } // ... ViewHolder and other adapter methods ... @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { YourMatchItem currentItem = matchItems.get(position); String championKey = currentItem.getChampionKey(); // Your method to get the key // Get the champion ID using the key String championId = championKeyToIdMap.get(championKey); if (championId != null) { // Construct the image URL using the DDragon CDN String championImageUrl = "http://ddragon.leagueoflegends.com/cdn/9.22.1/img/champion/" + championId + ".png"; // Load the image with Picasso Picasso.get() .load(championImageUrl) .placeholder(R.drawable.champion_placeholder) // Optional: placeholder image .error(R.drawable.champion_error) // Optional: error image .into(holder.championImageView); } else { // Handle cases where the key isn't found holder.championImageView.setImageResource(R.drawable.unknown_champion); } } public static class ViewHolder extends RecyclerView.ViewHolder { ImageView championImageView; public ViewHolder(@NonNull View itemView) { super(itemView); championImageView = itemView.findViewById(R.id.champion_image); } } }
Quick Notes:
- Add Picasso to your project dependencies (in
build.gradle):implementation 'com.squareup.picasso:picasso:2.71828' - Ensure
champion.jsonis placed in theassetsdirectory of your Android project (create the directory if it doesn't exist). - For newer Android SDKs, enable cleartext traffic in
AndroidManifest.xmlto load HTTP URLs (or use HTTPS for production).
内容的提问来源于stack exchange,提问作者1haker

