当我在champion.json中具有特定行的“键”时,从JSON文件获取“ id”

时间:2019-11-19 11:48:24

标签: 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 = 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");

已编辑 这是我已经有我的“钥匙”的班级:

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;
}

}

2 个答案:

答案 0 :(得分:0)

尝试此代码。我的解决方案是解析数据对象并测试id是否等于输入

输入:idInput =“ 266”

输出:键==> Aatrox

    JSONParser parser = new JSONParser();
    String JsonString = "{\n" +
            "  \"type\": \"champion\",\n" +
            "  \"format\": \"standAloneComplex\",\n" +
            "  \"version\": \"9.22.1\",\n" +
            "  \"data\": {\n" +
            "    \"Aatrox\": {\n" +
            "      \"version\": \"9.22.1\",\n" +
            "      \"id\": \"Aatrox\",\n" +
            "      \"key\": \"266\",\n" +
            "      \"name\": \"Aatrox\",\n" +
            "      \"title\": \"the Darkin Blade\"\n" +
            "    }\n" +
            "  }\n" +
            "}";
    JSONObject jsonObject = (JSONObject) parser.parse(JsonString);

    JSONObject dataJsonObject = (JSONObject) jsonObject.get("data");

    //All keys ( aatrox , annie , ... )
    Set<String> keys = dataJsonObject.keySet();

    String idInput = "266" ;

    for(String key : keys ) {

        JSONObject jsonKey = (JSONObject)dataJsonObject.get(key) ;

        String idJsonObject = (String) jsonKey.get("key") ;

        if(idJsonObject.equals(idInput)) {
            System.out.println("key == > " + key);
            break ;
        }

    }

答案 1 :(得分:0)

使用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());
    }
}

build.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());
}