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
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.
I am using org.json.simple.parser JSON Parser. One specific data contained very large numbers. For example it once failed while parsing a line with this error
java.lang.NumberFormatException: For input string: "982134839798321390034432432"
Clearly it should be parsed with BigInt data type. Or there should be an option to treat these just as strings. What can be done in this case?
This is a known issue in "json-simple", see https://github.com/fangyidong/json-simple/issues/73
You need to either:
Switch to a different JSON parser, for example https://github.com/FasterXML/jackson
Apply the patch on issue #73 to a private fork of "json-simple" and use that instead of the released version, or use "loegering"s fork at https://cliftonlabs.github.io/json-simple/ (linked from issue #73)
So I want to parse flightradar24.com data into a Java program. The data seems to be JSON-ish and thus I am trying to read it using GSONs JSonParser.
Here is a short excerpt of what I try to parse (you can see it in full e.g. in http://arn.data.fr24.com/zones/italy_all.js?callback=pd_callback):
pd_callback({"45da286":["4CAAB6",43.5609,12.6837,211,34975,420,"7311","F-LIBP2","B772","EI-ISA",1411143824,"NRT","FCO","AZ785",0,0,"AZA785",0],
"45dae4b":["7809B9",47.5892,15.8256,204,36000,442,"7303","F-LKTB2","A332","B-5921",1411143824,"PVG","FCO","MU787",0,0,"CES787",0],
"45dae73":["76CEF7",47.6238,17.2440,291,36000,428,"0342","F-LKTB1","B77W","9V-SWW",1411143826,"SIN","LHR","SQ318",0,0,"SIA318",0],
"45db3e2":["71BC61",46.0211,10.0549,242,22800,344,"7313","F-LIPE1","B744","HL7461",1411143824,"ICN","MXP","KE927",0,-2176,"KAL927",0],
"full_count":10394,"version":4});
Each line in the example above resembles the data of a certain flight at that moment, with id, lat, lon, and so on. I have removed pd_callback(...); and just to try it I removed ""full_count":10394,"version":4" as well. When I try to parse this string to an iterable JSON Object Array, e.g. like this:
com.google.gson.JsonParser jsonParser = new JsonParser();
com.google.gson.JsonArray jsa = jsonParser.parse(line).getAsJsonArray();
I always get parsing errors. I think one of the problems is that the field names are not given and the syntax might be wrong, but thats actually how flightradar reads the data. In the end, I just want to be able to iterate through each flight and to read each attribute as a primitive to then feed it into my own objects.
Anyone with an idea where the problem is or how I can parse this kind of data conveniently? Any comments appreciated.
I am trying to convert string like this:
{"Shops":[
{"city":"Riga","shops":[{"a":"some info here","b":"...","c":"..."},{"a":"some info here","b":"...","c":"..."}]},{"city":"Liepaja","shops":[{"a":"info here","b":"info....","c":"..."}]
]}
to 2d array, like
shops[0][0]=>{"a":"some info here","b":"...","c":"..."}
shops[1][0]=>{"a":"info here","b":"info....","c":"..."}
Is it possible? Is there some easy way to do that?
I've searched, tried, but I still don't know how to do that.
I'm new in java.
That is a JSON string. There are a number of libraries that will do this for you.
JSON in Java
GSON
That looks like JSON data, and you should treat it as such.
Try a JSON parsing library for Java. I like GSON for its simplicity. Take a look at the Gson.fromJson() set of methods.
The type of data you have posted is JSON encoded. you could use a json encoder and decoder to do this job easily.
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