我有一个获取最强Wifi访问点信号的方法,其中avialabe是并返回SSID字符串,所有这些SSID字符串都存储在JSON文件的原始文件夹中:如何访问raw文件夹中的文件并解析如果SSID“FR WLAN”是?
,它与Gson一起得到例如route_number 6ssid_number JSON文件:
{
"data": [
{
"ssid": "KD Privat",
"route_number": 1
},
{
"ssid": "KD WLAN Hotspot",
"route_number": 4
},
{
"ssid": "FR WLAN",
"route_number": 6
}
]
}
WifiJSON课程:
public class WifiJSON {
private String ssid;
private int route_number;
public WifiJSON(String ssid, int route_number) {
this.ssid = ssid;
this.route_number = route_number;
}
private String getSsid() {
return ssid;
}
private void setSsid(String ssid) {
this.ssid = ssid;
}
private int getRoute_number() {
return route_number;
}
private void setRoute_number(int route_number) {
this.route_number = route_number;
}
@Override
public String toString() {
return "WifiJSON [ssid=" + ssid + ", route_number=" + route_number
+ "]";
}
}
MainActivity中的parse_SSID:
//parse the storeed json file"ssid_number" and get the route_number back.
private int parse_SSID(String route_string) {
// TODO Auto-generated method stub
InputStream is = getResources().openRawResource(R.raw.ssid_number);
Gson gson = new Gson();
WifiJSON obj = gson.fromJson(route_string, WifiJSON.class);
return 0;
}
}
WiFiJSONList类:
import java.util.ArrayList;
public class WiFiJSONList {
private ArrayList<WifiJSON> data;
public ArrayList<WifiJSON> getWifiList() {
return data;
}
public void setWifiList(ArrayList<WifiJSON> wifiList) {
this.data = wifiList;
}
}
答案 0 :(得分:1)
我尝试了你的代码,并进行了一些修改。这对我有用。 为了检查目的,我已经硬编码了json字符串。您可以从raw或assets文件夹中读取并继续前进。
private int parse_SSID(String route_string) {
// TODO Auto-generated method stub
Gson gson = new Gson();
WiFiJSONList obj = gson.fromJson(route_string, WiFiJSONList.class);
//Now iterate through the list
List<WiFiJSON> wifijson = obj.getWifiList();
Iterator iterator = wifijson.iterator();
while (iterator.hasNext()) {
WiFiJSON wifielement = (WiFiJSON) iterator.next();
System.out.println(wifielement.getSsid() + "----" + wifielement.getRoute_number());
}
return 0;
}
用法将是这样的:(实际上,在使用gson解析json时,您的json字符串应该是单个对象,而不是直接使用数组。)
String json = "{\"data\": [{\"ssid\": \"KD Privat\",\"route_number\": 1},{\"ssid\": \"KD WLAN Hotspot\",\"route_number\": 4},{\"ssid\": \"FR WLAN\",\"route_number\": 6}]}";
parse_SSID(json);
public class WiFiJSON {
private String ssid;
private int route_number;
public String getSsid() {
return ssid;
}
public void setSsid(String ssid) {
this.ssid = ssid;
}
public int getRoute_number() {
return route_number;
}
public void setRoute_number(int route_number) {
this.route_number = route_number;
}
}
public class WiFiJSONList {
private ArrayList<WiFiJSON> data;
public ArrayList<WiFiJSON> getWifiList() {
return data;
}
public void setWifiList(ArrayList<WiFiJSON> wifiList) {
this.data = wifiList;
}
}
如果有效,请告诉我。