Reputation: 1
I am trying to use the value of rate in the below JSON object as my variable.
URL is : http://rate-exchange-1.appspot.com/currency?from=USD&to=INR
Output of above URL is like " {"to": "INR", "rate": 64.806700000000006, "from": "USD"} ". I am assuming it as JSON object. how to get the value of 64, shall i get it by parsing?
Upvotes: 0
Views: 197
Reputation: 12491
There're many options to deserialize JSON as mentioned in other answers, most of the time it would be better to define a corresponding Java class and then do serialization/deserialization. One example implementation with Gson would be:
public class Main {
public static void main(String[] args) {
Gson gson = new Gson();
String jsonString = "{\"to\": \"INR\", \"rate\": 64.806700000000006, \"from\": \"USD\"}";
CurrencyRate currencyRate = gson.fromJson(jsonString, CurrencyRate.class);
}
class CurrencyRate {
private String from;
private String to;
private BigDecimal rate;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public BigDecimal getRate() {
return rate;
}
public void setRate(BigDecimal rate) {
this.rate = rate;
}
}
}
And Gson is Thread Safe
, so it's OK to init only one Gson instance and share it among all threads.
Upvotes: 1
Reputation: 5086
You can use JSONObject
to convert strings into objects.
String responseString = "{'to': 'INR', 'rate': 64.806700000000006, 'from': 'USD'}";
JSONObject responseObject = new JSONObject(responseString);
Log.d("Response",responseObject.getString("rate")); //64.806700000000006
Upvotes: 1
Reputation: 121599
Q: how to get the value of 64, shall i get it by parsing?
A: Yes.
SUGGESTION:
You can also deserialize it into a Java object.
There are many libraries that support this, including:
JSONOjbect (Android)
Upvotes: 0