I got a different type of numbers in my json string. So parsing this numbers with JSONObject leads to 3.7E-4-like representation of this numbers. I prefer to see numbers as a string. What to do? How to prevent such conversion?
{"data":
{"number1":0.0004,
"number2":0.00038,
"number3":0.00037
}}
Simply, create a string before putting your number to JSON.
or
int number = 0;
json.put(number + "");
Can you give an example number, not represented like above?
I think it is some limitation of this particular json library. As a workaround, you could convert parsed values to BigDecimal and use it, unless the double conversion does not lose precision significantly.
For more details read this: How to prevent JSONObject from json.jar converts decimal numbers string into double
Related
I know that most Java json libraries can pretty print by
parsing into a generic model and then
serialising the model.
There are endless existing questions on StackOverflow which tell you to pretty print json this way using Jackson or GSON, e.g Pretty-Print JSON in Java
However, I have found with using Jackson ObjectMapper to do this, if I have decimal value eg "10000.00" it will then parse them into either a BigDecimal or Double and then end up writing it as "10000.0" (double) or "1E+4" (BigDecimal).
What I want is a way of formatting JSON which only affects whitespace, and does not disturb the content of any values - if the input was "10000.00" the output must be "10000.00"
Does anyone know of a Java JSON library that can handle that?
Underscore-java library has static method U.formatJson(json). It will leave the double value as is. 12.0 will be formatted as 12.0. I am the maintainer of the project.
There is a difference between JSONs {"value":5.0} and {"value":"5.0"} in the second case the "5.0" value will be treated as String and will not be modified. In the first case, it will be detected as Numerical and may be modified. So, either make a requirement for your JSON to have numerical values quoted, or do it yourself in your code before parsing the JSON string. Also if you yourself produce the JSON from some object then if you have
private Double myValue;
Have the getter
#JsonIgnore
Double getMyValue() {
return myValue;
}
and add another getter
#JsonProperty(name="myValue")
String getMyValueStr() {
return myValue.toString();
}
All annotations are for Jason-Jackson.
After a few weeks i finally found out how to parse my numbers through my app. But now the app crashes when given a number in the following format: 92839283982938 or 22.483.84.3883.
I just dont know how to make it accept those number formats. The problem is connected to a barcode scanner, so i really need it to accept those number formats.
The code i used to parse is:
JSONObject c = user.getJSONObject(Integer.parseInt(xyz)-1);
For longer number you should use Long.parseLong() instead of Integer.parseInt().
Next case 22.483.84.3883 not a numeric. You will get NumberFormatException from here.
You can use
try{
long val=Long.parseLong("xxxx")
}catch(NumberFormatException e){
// exception
}
If you want to consider 22.483.84.3883 or 22-483-84-3883 as a valid case, you need to replace . or - first.
Eg:
long val=Long.parseLong("22.483.84.3883".replaceAll("\\.", ""));
System.out.println(val);
Use Long.parseLong instead. Integer type can't contain such large numbers (the max value of Integer is 2^31-1, which is much smaller than 92839283982938). In addition, you should eliminate the dots.
Try :
JSONObject c = user.getJSONObject(Long.parseLong(xyz.replace(".",""))-1);
I am reading a legacy webservice that returns doubles in a format I am not familiar with.
some examples are
1.58e-6
1.56e-6
1.45e-6
They should represent doubles like these (for example)
0.000004343
What is this format and how it can be converted?
You can convert like this
1.58e-6=1.58*10^-6=0.00000158
Ok, it was actually rather simple.
double dbl = 1.45e-6;
DecimalFormat df = new DecimalFormat("#.########");
System.out.println(df.format(dbl));
outputs : 0.00000145
It's called scientific notation. Double.parseDouble() can handle it. NB they're not doubles, they are real numbers expressed in text in scientific notation. Double is the target format you want, not this format.
try this
String s = new DecimalFormat("0.##############").format(Double.parseDouble("1.58e-6"));
How to get an Integer instead of Long from JSON?
I want to read JSON in my Java program, but when I get a JSON value which is a number, my parser returns a number of type Long.
I want to get an Integer. I tried to cast the long to an integer, but java throws a ClassCastException (java.lang.Long cannot be cast to java.lang.Integer).
I tried several things, such as first converting the long to a string, and then converting with Integer.parseInt(); but also that doesn't work.
I am using json-simple
Edit:
I still can't get it working. Here is an example:
jsonItem.get("amount"); // returns an Object
I can do this:
(long)jsonItem.get("amount");
But not this:
(int)jsonItem.get("amount");
I also can't convert it with
Integer newInt = new Integer(jsonItem.get("amount"));
or
Integer newInt = new Integer((long)jsonItem.get("amount"));
Please understand that Long and Integer are object classes, while long and int are primitive data types. You can freely cast between the latter (with possible loss of high-order bits), but you must do an actual conversion between the former.
Integer newInt = new Integer(oldLong.intValue());
I tried
(int)(long)jsonItem.get("amount");
and it worked for me
I am working on a project that requires some simple math to be performed on currency, however it arrives in the form of a String. I am new to Java/Android so I am looking for help in converting from a String to a data type appropriate to this operation. At first I thought Float was right but after reading elsewhere and introducing myself to the numbers class, it appears BigDecimal is correct. Am I on the right track? At this point I simply want to subtract the sum of payments from an initial invoice amount. I get the feeling this code is simple but clumsy and I suspect I am missing a great deal about the nuances of working with currency. How would you do it? All advice warmly appreciated!
// capture variables from sending activity
String invoiceAmt = getIntent().getStringExtra("invoiceAmt");
String paymentsSum = getIntent().getStringExtra("paymentsSum");
// convert strings to BigD's
BigDecimal amt = new BigDecimal(invoiceAmt);
BigDecimal sum = new BigDecimal(paymentsSum);
// Do the math
BigDecimal invDue = amt.subtract(sum);
// insert the value (back to string) into textView
TextView tvInvoiceDue = (TextView)findViewById(R.id.InvoiceDue);
tvInvoiceDue.setText(invDue.toString());
BigDecimal is a fine approach. So is using an int or a long to store cents. I've heard some people like Joda-Money but I've never used it myself.
See this question.
In the code you posted, make sure the Strings you are receiving don't have currency symbols in them.