When we use automated testing, it is inevitable to interact with the server to obtain the server's data, which is the need to parse the JSON data. The following is the relevant code
public class Parsejson {
public static arraylist<priceinfo> ArrayList = new arraylist<priceinfo> ();
Public double Get_price (string string) throws Jsonexception {
Double price=0;
Request JSON data
String jsonstring = Util_json (URL);
if (jsonstring! = null) {
Start parsing JSON data
Parsejson (jsonstring);
Data is in ArrayList after parsing is complete
// 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", "exchange rate is" + 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;
}
}
}
uiautomator-parsing JSON data