在我们使用自动化测试时,难免会与服务器交互,获取服务器的数据,这是就要是解析json数据。以下是相关代码
public class ParseJson {
public static ArrayList<PriceInfo> arrayList = new ArrayList<PriceInfo>();
public double get_price(String string) throws JSONException {
double price=0;
//请求json数据
String jsonString = Util_json(URL);
if(jsonString != null){
//开始解析json数据
parseJson(jsonString);
// 解析完成以后 数据都在arrayList中
// System.out.println("arrayList.size = " + arrayList.size());
for(int i=0;i<arrayList.size();i++){
PriceInfo str = arrayList.get(i);
if(str.name.equals(string))
{
price = str.getPrice();
}
}
}
Log.v("aaa","汇率是"+ price);
return price;
}
public static void parseJson(String jsonString) throws JSONException {
JSONObject object = new JSONObject(jsonString);
JSONArray jsonArray = object.getJSONArray("value");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String ts = jsonObject.getString("ts");
String price = jsonObject.getString("price");
String name = jsonObject.getString("name");
PriceInfo info = new PriceInfo(ts, Double.parseDouble(price), name);
arrayList.add(info);
}
}
public static String Util_json(String url) {
StringBuilder json = new StringBuilder();
try {
URL urlObject = new URL(url);
URLConnection uc = urlObject.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
uc.getInputStream()));
String inputLine = null;
while ((inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}
static class PriceInfo {
String ts;
double price;
String name;
public PriceInfo(String ts, double price, String name) {
super();
this.ts = ts;
this.price = price;
this.name = name;
}
public String getTs() {
return ts;
}
public void setTs(String ts) {
this.ts = ts;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}