0

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?

3 Answers3

1

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:

paulsm4
  • 114,292
  • 17
  • 138
  • 190
1

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
easeccy
  • 4,248
  • 1
  • 21
  • 37
  • You have the wrong language here. The OP is using Java not JavaScript – bhspencer Apr 02 '17 at 23:48
  • 2
    This requires that you download a JSON library (like Jackson, JSON, etc). In this case, the library is [JSON]: https://mvnrepository.com/artifact/org.json/json – paulsm4 Apr 02 '17 at 23:53
  • I'm using JSONObject without downloading any library in Android Studio 2.3 . – easeccy Apr 02 '17 at 23:59
  • 1
    The OP only says they are using Java not Android studio. JSONObject is not part of the standard Java libraries. – bhspencer Apr 03 '17 at 00:13
1

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.

shizhz
  • 11,715
  • 3
  • 39
  • 49