我正在尝试在Android上创建货币转换器应用。 我从api获取此字符串请求
{"base":"USD","date":"2018-07-27","rates":{"RON":3.9819354839}}
我想以某种方式解析此字符串(使用json)并获得RON值
这是我的代码:
public class MainActivity extends AppCompatActivity {
Button convert;
TextView textView;
RequestQueue requestQueue;
Spinner spinner;
Spinner spinner2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner=(Spinner)findViewById(R.id.spinner);
spinner2=(Spinner)findViewById(R.id.spinner2);
final EditText textBox1 = (EditText)findViewById(R.id.editText);
final EditText textBox2 = (EditText)findViewById(R.id.editText2);
final TextView textView=(TextView)findViewById(R.id.textView);
Button convert = (Button)findViewById(R.id.button);
Cache cache = new DiskBasedCache(getCacheDir(),1024*1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue=new RequestQueue(cache,network);
requestQueue.start();
convert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text1 = spinner.getSelectedItem().toString();
String text2= spinner2.getSelectedItem().toString();
String URL ="https://exchangeratesapi.io/api/latest?base="+text1+"&symbols="+text2;
StringRequest stringRequest= new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
textView.setText(response);
Log.e("Rest response", response.toString());
// requestQueue.stop();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textView.setText("error......");
error.printStackTrace();
}
});
requestQueue.add(stringRequest);
}
});
}
}
答案 0 :(得分:0)
我设法解决了这个问题!也许这也会对其他人有帮助。
JSONObject obj = new JSONObject(response);
JSONObject ratesObj = obj.getJSONObject("rates");
String currency = ratesObj.getString(convertedValue);