java - 当 Champion.json 中的特定行有 "id"时,从 JSON 文件获取 "key"

标签 java android json android-studio

这是我的 JSON 文件:http://ddragon.leagueoflegends.com/cdn/9.22.1/data/en_US/champion.json

JSON 有一个 ID 和 Name 作为两个键以及一些其他键。例如,

{
  "type": "champion",
  "format": "standAloneComplex",
  "version": "9.22.1",
  "data": {
    "Aatrox": {
      "version": "9.22.1",
      "id": "Aatrox",
      "key": "266",
      "name": "Aatrox",
      "title": "the Darkin Blade"
    }
  }
}

因此,对于给定的 key ,例如“key=266”,我想要 id="Aatrox"。

我找到了这段代码:

public String loadJSONFromAsset(Context context) {
    String json = null;
    try {
        InputStream is = context.getAssets().open("champion.json");

        int size = is.available();

        byte[] buffer = new byte[size];

        is.read(buffer);

        is.close();

        json = new String(buffer, "UTF-8");


    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;

}

我正在尝试这个:

JSONObject obj = new JSONObject(loadJSONFromAsset(context));

JSONArray m_jArry = obj.getJSONArray("data");

JSONObject jo_inside = m_jArry.getJSONObject(key); 

String champName = jo_inside.getString("id");

已编辑 这是我的类(class),我已经有了我的“ key ”:

public class MatchListAdapter extends ArrayAdapter<Match> {

private static final String TAG = "MatchListAdapter";

private Context mContext;
private int mResource;
private int lastPosition = -1;
String championName;

public MatchListAdapter(Context context, int resource, ArrayList<Match> objects){
    super(context, resource, objects);
    mContext = context;
    mResource = resource;
}

@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    //Get the champions information
    String gameType = getItem(position).getGameType();
    int key = getItem(position).getKEY();
    String sex = getItem(position).getSex();

    LayoutInflater inflater = LayoutInflater.from(mContext);
    convertView = inflater.inflate(mResource, parent, false);

    TextView tvName = convertView.findViewById(R.id.testName);
    TextView tvBirthday = convertView.findViewById(R.id.textView2);
    TextView tvSex = convertView.findViewById(R.id.textView3);
    ImageView championIMG = convertView.findViewById(R.id.championImage);

    //Get name from champion.json using my "key" and then load imgage using Picasso

    Picasso.get()
            .load("http://ddragon.leagueoflegends.com/cdn/9.22.1/img/champion/"+championName+".png")
            .resize(100,100)
            .placeholder(R.drawable.ic_launcher_background)
            .into(championIMG, new Callback() {
                @Override
                public void onSuccess() {
                }

                @Override
                public void onError(Exception e) {
                    Log.d("error", "error Message: "+e.getMessage());
                }
            });

    tvName.setText(gameType);
    tvBirthday.setText("id: " + key);
    tvSex.setText(sex);

    return convertView;
}

}

最佳答案

借助 Google 的 Gson 库,您可以解析任何有效的 JSON 并简单地遍历键。

import java.io.*;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import com.google.gson.*;

public class ChampionSearch {
    public static void main(String[] args) {
        InputStream stream = ChampionSearch.class.getClassLoader().getResourceAsStream("champion.json");
        InputStreamReader reader = new InputStreamReader(stream);
        JsonObject json = JsonParser.parseReader(reader).getAsJsonObject();
        Entry<String, JsonElement> found = findFirst(json, "key", "266");
        System.out.printf("Found: %s%n", getValueForKey(found.getValue(), "id"));
    }

    public static String getValueForKey(JsonElement data, String key) {
        return data.getAsJsonObject().get(key).getAsString();
    }

    public static Entry<String, JsonElement> findFirst(JsonObject json, String key, String value) {
        return findAll(json, key, value).iterator().next();
    }

    public static Set<Entry<String, JsonElement>> findAll(JsonObject json, String key, String value) {
        return json.getAsJsonObject("data").entrySet().stream().filter(entry -> {
            return entry.getValue().getAsJsonObject().get(key).getAsString().equals(value);
        }).collect(Collectors.toSet());
    }
}

构建.gradle

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    compile 'com.google.code.gson:gson:2.8.6'
}
<小时/>

您还可以通过提供模板类作为第三个参数来使值检索变得通用。

System.out.printf("Found: %s%n", getValueForKey(found.getValue(), "id", String.class));
@SuppressWarnings("unchecked")
public static <T> T getValueForKey(JsonElement data, String key, Class<T> clazz) throws IllegalArgumentException {
    JsonElement element = data.getAsJsonObject().get(key);

    if (Integer.class.equals(clazz)) {
        return (T) new Integer(element.getAsInt());
    } else if (Double.class.equals(clazz)) {
        return (T) new Double(element.getAsInt());
    } else if (Boolean.class.equals(clazz)) {
        return (T) new Boolean(element.getAsBoolean());
    } else if (String.class.equals(clazz)) {
        return (T) element.getAsString();
    }

    throw new IllegalArgumentException("Could not get value of type: " + clazz.getSimpleName());
}

关于java - 当 Champion.json 中的特定行有 "id"时,从 JSON 文件获取 "key",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58933424/

相关文章:

javascript - 从json中获取具体数据

java - 无法从jedis获取资源

android - 用户没有资格购买此 android inapp 购买

javascript - 将 JSON 从 angular.js 发送到 node.js

android - Nativescript Android 模拟器未运行

php - HTTP Post 将 € 转换为 ?象征

javascript - Typeahead.js - 预取动态 php 生成的 JSON

java - 在 ConstraintLayout 上添加 facebook 受众网络横幅时出错

java - 在 Android 中检查文件是否存在不起作用

java - 如何在单个 Controller 中制作多个@PatchMapping?