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?

2

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

4 Comments

You have the wrong language here. The OP is using Java not JavaScript
This requires that you download a JSON library (like Jackson, JSON, etc). In this case, the library is [JSON]: mvnrepository.com/artifact/org.json/json
I'm using JSONObject without downloading any library in Android Studio 2.3 .
The OP only says they are using Java not Android studio. JSONObject is not part of the standard Java libraries.
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.

Comments

0

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:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.