您可以使用以下代码示例来完成您的任务
Type listType = new TypeToken<List<Country>>() {}.getType();
Gson gson = new Gson();
String json = "["
+ "{\"CountryID\" : \"3\",\"CountryName\" : \"China\"},"
+ "{\"CountryID\" : \"2\",\"CountryName\" : \"Japan\"},"
+ "{\"CountryID\" : \"1\",\"CountryName\" : \"Australia\"},"
+ "{\"CountryID\" : \"4\",\"CountryName\" : \"India\"},"
+ "{\"CountryID\" : \"5\",\"CountryName\" : \"Holland\"}"
+ "]";
// parsing the JSON array
ArrayList<Country> countries = gson.fromJson(json, listType);
System.out.println(countries);
// sorting the country list based on CountryID. Ensure list is sorted, since we do binary search next
Collections.sort(countries);
System.out.println(countries);
Country searchKey = new Country(3,"");
// searching for country with ID 3
int index = Collections.binarySearch(countries, searchKey);
if(index < 0 || index >= countries.size() ) System.out.println("Country with ID "+searchKey.getCountryID()+ " not found in results");
else
{
System.out.println("Found Country with ID : " + searchKey.getCountryID()+ " @ index : " + index);
Country searchResult = countries.get(index);
System.out.println("Searched result : "+searchResult);
}
- 这里我使用GSON来解析
Country
列表
- 为此,我使用了一个名为的数据持有者类
Country
找到班级Country
public class Country implements Comparable<Country> {
public Country(int countryID, String countryName) {
super();
CountryID = countryID;
CountryName = countryName;
}
//"CountryID" : "1","CountryName" : "Australia"
private int CountryID;
private String CountryName;
/**
* Gets the countryID.
*
* @return <tt> the countryID.</tt>
*/
public int getCountryID() {
return CountryID;
}
/**
* Sets the countryID.
*
* @param countryID <tt> the countryID to set.</tt>
*/
public void setCountryID(int countryID) {
CountryID = countryID;
}
/**
* Gets the countryName.
*
* @return <tt> the countryName.</tt>
*/
public String getCountryName() {
return CountryName;
}
/**
* Sets the countryName.
*
* @param countryName <tt> the countryName to set.</tt>
*/
public void setCountryName(String countryName) {
CountryName = countryName;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Country [CountryID=" + CountryID + ", CountryName="
+ CountryName + "]";
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(Country o) {
// TODO Auto-generated method stub
return this.getCountryID()-o.getCountryID();
}
}
Country
类实现Comparable
接口来执行Collections
'二进制搜索
- 解析成功后,我对
Country
列表进行了排序
- 然后使用
binarySearch
ofCollections
类找到你的索引search-key-country
- 现在只需使用返回
index
的来检索您的search-result-country
对象