pretty print JSON using java, without formatting the values - java

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.

Related

Does a response containing multiple json Values always have to be wrapped in an array in java?

I am trying to return a response from the back end using java where the response is a list of json values.
Is it possible to return the data in this format?
{"someKey": someValue},
{"someKey2": someValue},
{"someKey2": someValue}
I noticed that json values are always returned wrapped in an array like this
[
{"someKey": someValue},
{"someKey2": someValue},
{"someKey2": someValue}
]
I was asked to return the json data without being in an array and I am having trouble doing that. Is it even possible to return a list of json objects without being wrapped in an array? This is in java using the ObjectMapper class
List of json objects not wrapped in an array [] is a invalid json format and will give you error: multiple JSON root elements
Possibly you can modify the result to this JSON format?
{
"somekey": somevalue,
"someKey2": someValue,
"someKey3": someValue,
}
As others have pointed out, a list of objects without the wrapping array.would be invalid JSON.
However, if you really must return that, you could arrange to get the JSON as a String, and then use String methods, of your choice (e.g. substring) to remove the square braces, and then return that. Ultimately, a JSON is a String.

How can I export a JSON string with floats in the format 5.0f?

I'm trying to make a Minecraft function compiler in Java, and data tags in Minecraft are very similar to JSON objects, but not quite the same. In general, they follow the JSON format, so I've been using JSONObjects, but for some reason, it wants me to have an 'f' after each float to show that they're floats, contrary to JSON standard of just writing the number.
Is it possible to export a JSON string with floats in that format without re-writing the whole exporter? If not, what's the best way to do this without writing spaghetti code? I will not need to re-parse it in Java.

Convert all the number values to string in JSON using Java

I need to convert all the number values to string in my JSON file to overcome a NumberFormatException due to exceeding the Long.Max_Value limit. I am using json-simple JSONParser and it throws an exception. What's the best way to convert them in Java?
At the moment, I can't even parse the file completely due this exception.
look this examples https://sites.google.com/site/gson/gson-user-guide . Google gson library is probably what you need:
can convert object to json
can convert json to object
and many other functions

org.json.JSONObject messing with data

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

How can I serialize a Java object to a escaped JSON string?

Is there a way to convert a Java object to a string like below?
Note that all the filed names should be escaped, and "\n" is used as to separate records.
{
"content":"{\"field1\":123, \"field2\":1, \"field3\":0, \"field4\":{\"sub1\":\"abc\", \"sub2\":\"xyz\"}}\n
{\"field1\":234, \"field2\":9, \"field3\":1, \"field4\":{\"sub1\":\"xyz\", \"sub2\":\"abc\"}}"
}
Thanks,
You can use GSON for that task.
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
If you need to have a better readable representation, you may use the pretty-print feature.
Gson gson = new GsonBuilder().setPrettyPrinting().create();
To realize something like your example, you could in a first step serialize your content class, put the resulting string as a property in another class and serialize that one again.
That way GSON takes care of the escaping of ".
If you collect your strings in an array and use the pretty print option shown above, you get something similar to your line-break requirement, but not quite the exact same.
The result of the process described above may look like the following:
{
"content": [
"{\"field1\":123, \"field2\":1, \"field3\":0, \"field4\":{\"sub1\":\"abc\", \"sub2\":\"xyz\"}}",
"{\"field1\":234, \"field2\":9, \"field3\":1, \"field4\":{\"sub1\":\"xyz\", \"sub2\":\"abc\"}}"
]
}
Another alternative is to use the Json-lib library http://json-lib.sourceforge.net
String jsonStrData = " ....... ";
JSONObject jsonObj = JSONObject.fromObject(jsonStrData);
System.out.println(jsonObj);
Like GSON, json-lib handles escaping for you, more info on how to use it here http://json-lib.sourceforge.net/usage.html

Categories