Jackson - Read different object one by one from file - java

I have a file like this:
[{
"messageType": "TYPE_1",
"someData": "Data"
},
{
"messageType": "TYPE_2",
"dataVersion": 2
}]
As you can see there is a file which contains different types of JSON objects. I also have an ObjectMapper which is able to parse the both types. I have to read the JSon objects one by one (because this file can be pretty huge) and to get the right Object (Type1Obj or Type2Obj) for each of them.
My question is how I could achieve with Jackson to read the JSon objects one by one from the file.

You could read the array as a generic Jackson JSON object similar to
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonData);
then traverse all the children of the array using
rootNode#elements()
and parse every one of the JsonNode children into the respective type using a check of messageType similar to
if ("TYPE_1".equals(childNode.get("messageType")) {
Type1Class type1 = objectMapper.treeToValue(childNode, Type1Class.class);
} else // ...

Related

How to convert a JSON to Java object but with translated values

I have a JSON like below and I want to generate the Java object of the respective class by parsing it. The catch is that I don't want the value for maxtime in that object to be set as {{ Instant.MAX.toString()}}, but it should be its translated value, which means it should be +1000000000-12-31T23:59:59.999999999Z. Is there any standard library to achieve this similar requirement or I will have to write a customized code for this?
{
"key1": "",
"key2": "",
"key3": {
"maxTime": "{{ Instant.MAX.toString()}}",
"anotherKey": "{{MyProjectUtils.getKey()}}"
}
}
In the worst case, I am ready to replace this JSON file with some other type of file but at the end, I want a java object with translated values.
You may create a JavaBean/POJO object from a JSON file. You may adjust the members in POJO Object according to the JSON File.
here is how to create a POJO object from a JSON file.

Use GSON to parse json objects into java.util.HashMap

I am trying to parse a json object with this format:
{
'result': (json array or json object) ,
}
The code I am using to parse the json string is:
Map<String, Object> responseMap = new Gson().fromJson(
json,
new TypeToken<HashMap<String, Object>>() {}.getType()
);
When the result field is a JSON object checking with the following line of code returns "LinkedTreeMap"
// returns "LinkedTreeMap"
responseMap.get("result").getClass().getSimpleName()
Likewise, all nested JSON objects are parsed into com.google.gson.internal.LinkedTreeMap. Is there a way to make GSON parse JSON objects into java.util.HashMap by default instead of com.google.gson.internal.LinkedTreeMap.
The usual way to solve this problem seems to be to write a class that defines the structure I'd expect to see in the response JSON object. However, the value contained in the 'result' field can be a JSON object or a JSON array, and I do not have a standard format for the expected return objects and what they may contain.

How to get values from Json Object in Java?

I have stored an Json object in an String variable called output.
Assume,
String output;
This output variable is holding an json object.
below is the json object which output variable is holding.
How can access the price_currency which is in the prices?
"prices": [
{
"price_label": "",
"price_currency": "USD",
"price_wholesale": 32.00,
"price_retail": 70.00,
"price_currency_retail": "USD"
}
],
"deliveries": [{
"delivery_name": "Zappos Holiday",
"delivery_code": "",
"style_display_order": 2,
"season_name": "Holiday",
"season_year" : "2017",
"season_code": "",
"date_cancel": "",
"date_delivery_start": "",
"date_delivery_end": "",
"public": "0",
"style_comments": ""
},
There are many possibilities:
Converting the json in a bean (using libraries like Gson or Faster Jackson)
Converting the json in a Map (always using libraries like Gson or Faster Jackson)
Accessing directly the field you need using a regular expression (very complex)
Writing a parser
Using a library to access directly the field using Json path
Each of the previous possibilities has pro and cons.
For example if you need a particular field but you don't know the structure of the whole document you can use json path.
If you need to manage the whole json as an object to save it locally convert it to a bean.
And so on.
It is super simple, if you use the new javax.json package that was introduced in Java 7:
https://docs.oracle.com/javaee/7/api/javax/json/package-summary.html
Example:
JsonReader jsonReader = Json.createReader(new StringReader(yourString));
JsonArray prices = jsonReader.readArray();
for (JsonValue price : prices){
// ...
}
jsonReader.close();
Firstly you said your response value is a string output, here is the steps of parsing a JSON object in JAVA.
Parse your string value to JSONObject, let me name it jsonRet.
Then parse this
jsonRet.getJSONArray("prices")
This step you also get a JSON array of prices let me call it prices
Foreach the prices array as JSONObject
Then do
price.getString("price_currency")
This step you get a string value, this would be what you want.
For more info, I suggest you search key word Java JSON with Google that would be benefit for your understanding.
in java You have JSONObjet class which You can use in this case.
Some link to java doc --> click

Parse multiple JSON objects in one file

I have multiple JSON objects stored in one file separated by new line character (but one object can span over multiple lines) - it's an output from MongoDB shell.
What is the easiest way to parse them (get them in an array or collection) using Gson and Java?
Another possibility is to use Jackson and its ObjectReader.readValues() methods:
public <T> Iterator<T> readStream(final InputStream _in) throws IOException {
ObjectMapper mapper = new ObjectMapper();
// configure object mappings
...
// and then
return mapper.reader(MapObject.class).readValues(_in);
}
works pretty good on big enough (few gigabytes) JSON datafiles

Formatting JSON before writing to File

Currently I'm using the Jackson JSON Processor to write preference data and whatnot to files mainly because I want advanced users to be able to modify/backup this data. Jackson is awesome for this because its incredibly easy to use and, apparently performs decently (see here), however the only problem I seem to be having with it is when I run myObjectMapper.writeValue(myFile, myJsonObjectNode) it writes all of the data in the ObjectNode to one line. What I would like to do is to format the JSON into a more user friendly format.
For example, if I pass a simple json tree to it, it will write the following:
{"testArray":[1,2,3,{"testObject":true}], "anotherObject":{"A":"b","C":"d"}, "string1":"i'm a string", "int1": 5092348315}
I would want it to show up in the file as:
{
"testArray": [
1,
2,
3,
{
"testObject": true
}
],
"anotherObject": {
"A": "b",
"C": "d"
},
"string1": "i'm a string",
"int1": 5092348315
}
Is anyone aware of a way I could do this with Jackson, or do I have to get the String of JSON from Jackson and use another third party lib to format it?
Thanks in advance!
try creating Object Writer like this
ObjectWriter writer = mapper.defaultPrettyPrintingWriter();
You need to configure the mapper beforehand as follows:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
mapper.writeValue(myFile, myJsonObjectNode);
As per above mentioned comments this worked for me very well,
Object json = mapper.readValue(content, Object.class);
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
Where content is your JSON string response
Jackson version:2.12
To enable standard indentation in Jackson 2.0.2 and above use the following:
ObjectMapper myObjectMapper = new ObjectMapper();
myObjectMapper.enable(SerializationFeature.INDENT_OUTPUT);
myObjectMapper.writeValue(myFile, myJsonObjectNode)
source:https://github.com/FasterXML/jackson-databind

Categories

Resources