I am pretty new to json and normally donot use do much coding. I want a service which takes below json string as input
{
"var": "test11",
"_env": {
"activation": "wm6a93e3a80-0307-12cc-96e6-d79883bf841a",
"uuid": "48cdc2d0-0212-11e6-8315-d79883bf841a",
"eventID": 49167,
"recvTime": "Thu Apr 14 00:27:03 PDT 2016"
}
}
and spit out output as
{
"var": "test11"
}
and
{
"_env": {
"activation": "wm6a93e3a80-0307-12cc-96e6-d79883bf841a",
"uuid": "48cdc2d0-0212-11e6-8315-d79883bf841a",
"eventID": 49167,
"recvTime": "Thu Apr 14 00:27:03 PDT 2016"
}
}
The is just an example. It can contain more objects in json string and _env won't always appear at the end.
Is there any simple way to achieve using jackson API ?
Create a class to hold your JSON, like below:
public class Bar {
private String var;
@JsonProperty("_env")
private Object env;
public String getVar() {
return var;
}
public void setVar(String var) {
this.var = var;
}
public Object getEnv() {
return env;
}
public void setEnv(Object env) {
this.env = env;
}
}
And set the mapper to not fail on unknown properties before deserializing;
public static void main(String[] argv) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Bar bar = mapper.readValue(JSON, Bar.class);
}
This way, both when the _env is present or not, it will work.
If you need to "split" the json by each node, you can do something like this:
JsonNode node = mapper.readTree(JSON);
List<String> nodeJsons = new ArrayList<>();
Iterator<Entry<String, JsonNode>> nodeIterator = node.fields();
while (nodeIterator.hasNext()) {
Map.Entry<String, JsonNode> entry = nodeIterator.next();
nodeJsons.add(mapper.writeValueAsString(entry));
}
This way you will have a list of json strings in the end with every node serialized by itself, instead of one "big" json with everything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With