Reputation:
I am working on currency converter and trying to parse currencies from JSON String to double. As I explored, its issue with double quotes in JSON code, but I get this JSON from banks API and it can not be changed. I tried to use solution from another old question but it did not work (double vrijednostOne = Double.parseDouble(arr.getJSONObject(indexOne).getString("Srednji za devize"));) Is there any solution to parse JSON with double quotes to double?
btnPreracunaj.addActionListener(evtRacunaj -> {
//JSON Array - adds String input from StringBuilder
try {
arr = new JSONArray(response.toString());
int indexOne = comboOne.getSelectedIndex();
int indexTwo = comboTwo.getSelectedIndex();
String valutaOne = arr.getJSONObject(indexOne).getString("Valuta");
double vrijednostOne = Double.parseDouble(arr.getJSONObject(indexOne).getString("Srednji za devize"));
String valutaTwo = arr.getJSONObject(indexTwo).getString("Valuta");
double vrijednostTwo = Double.parseDouble(arr.getJSONObject(indexTwo).getString("Srednji za devize"));
System.out.println(valutaOne);
System.out.println(vrijednostOne);
System.out.println(valutaTwo);
System.out.println(vrijednostTwo);
} catch (JSONException e1) {
e1.printStackTrace();
}
});
There is JSON from API:
[
{
"Broj tečajnice": "190",
"Datum primjene": "03.10.2018",
"Država": "Australija",
"Šifra valute": "036",
"Valuta": "AUD",
"Jedinica": 1,
"Kupovni za devize": "4,612753",
"Srednji za devize": "4,626633",
"Prodajni za devize": "4,640513"
}
]
And this is exception:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "4,626633"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at Converter.lambda$0(Converter.java:136)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
...
Upvotes: 2
Views: 501
Reputation: 58
You can look the answer in below link. It uses locale to convert the string having ',' instead of '.' into double. the parse error is because Parsing string to double expect the decimal points in currency.
Converting different countrys currency to double using java
Upvotes: 2
Reputation: 51993
Since the currency prices seems to use a local format you need to use a number formatter with your locale (or rather the banks local)
NumberFormat format = NumberFormat.getInstance(new Locale("hr","HR"));
double price = format.parse(arr.getJSONObject(indexOne).getString("Srednji za devize"));
Based on a comment I used Croation as the locale but look here for a complete list of locales.
Upvotes: 2
Reputation: 6528
You can have a method:
currency = currency.substring(1, currency.length()-1);
double mainCurrency = Double.ParseDouble(currency);
Upvotes: -1