How to recursively parse json value in ObjectMapper.readValue? - java

I'm trying to parse json strings inside a json string into an Object using Jackson ObjectMapper. But I can't find a clean way to do this.
I have a SQL table storing Lists as json strings like "[1,2,3]". And I read all columns out into a Map then tries to use objectMapper.convertValue to make into a Java Object.
So here's a quick snippet to recreate the problem. Do note I don't control how the Map is generated in the actual code.
#Data
public class Main {
private List<Integer> bar;
public static void main(String[] args) throws Exception{
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> objectMap = new HashMap<String, Object>();
objectMap.put("bar", "[1,2,3]");
// Main foo = objectMapper.convertValue(objectMap, Main.class)
String json = objectMapper.writeValueAsString(objectMap);
Main foo = objectMapper.readValue(json, Main.class);
System.out.println(foo.getBar());
}
}
But this is not right. Instead of parsing the string, ObjectMapper tries to convert String to List directly and failed. I would expect foo.getBar() returns a List with 3 elements, but the code already failed at converting stage.

You should make "[1,2,3]" as String[] so:
"[1,2,3]".replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",")
Something like:
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> objectMap = new HashMap<String, Object>(){{
put("bar", "[1,2,3]".replaceAll("\\[", "")
.replaceAll("]", "")
.replaceAll("\\s", "").split(","));
}};
String json = objectMapper.writeValueAsString(objectMap);
Main foo = objectMapper.readValue(json, Main.class);
System.out.println(foo.getBar());
}
you just need to replace the "[1,2,3]" with what ever you getting it from.
Note: Not sure about the application logic

Related

ObjectMapper setSerializationInclusion(JsonInclude.Include.NON_NULL) setting is not reflected [duplicate]

This question already has answers here:
Excluding NullNode when serializing a Jackson JSON tree model
(3 answers)
Closed 11 months ago.
ObjectMapper still includes null values. I tried a lot of solutions found here, but nothing works. I cannot use json annotation, so my only solution is predefined setting of mapper, but this was not reflected. I thought this was due to caching of objectMapper. But my only modifies of mapper are made in Constructor. So caching would not be a problem
Dependencies:
Log4J2: 2.17.1
Fasterxml Jackson annotation: 2.13.2
Fasterxml Jackson databind: 2.13.2
Wildfly: 20.0.1
OpenJDK: 11.0.14.1
I have an objectMapper defined as global value which is instantiated in constructor. Then I have one method for building a JSON which accepts key and value. As value can by anything.
private final ObjectMapper jsonMapper;
public SomeConstructor() {
this.jsonMapper = new ObjectMapper();
this.jsonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
this.jsonMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
}
#Override
public void setJsonVar(String jsonVar, String jsonKey, Object values) {
// loads ObjectNode from memory if exists
ObjectNode jsonNode = getJsonVar(jsonVar);
// lazy init if ObjectNode not exists
if (jsonNode == null) {
jsonNode = jsonMapper.createObjectNode();
}
// add object
jsonNode.putPOJO(jsonKey, values);
}
Usage:
setJsonVar("var-A", "key-A", 1);
setJsonVar("var-A", "key-B", null);
print("var-a");
Expectation:
I want to avoid null values in JSON.
Expected: var-A: { "key-A":1 }
Got: var-A: { "key-A":1, "key-B":null }
Why does this happen and what can I do to work around this?
This option is applicable when serializing objects, custom objects or a Map for example, but not when working with json tree. Consider this Foo class:
public class Foo {
private String id;
private String name;
//getters and setters
}
The option to exclude nulls will work as expected with it.
Main method to illustrate it:
public class Main {
public static void main(String[] args) throws Exception {
serializeNulls();
System.out.println();
doNotSerializeNulls();
}
private static void serializeNulls() throws Exception {
ObjectMapper jsonMapper = new ObjectMapper();
Foo foo = new Foo();
foo.setId("id");
System.out.println("Serialize nulls");
System.out.println(jsonMapper.writeValueAsString(foo));
Map<String, Object> map = new LinkedHashMap<>();
map.put("key1", "val1");
map.put("key2", null);
System.out.println(jsonMapper.writeValueAsString(map));
}
private static void doNotSerializeNulls() throws Exception {
ObjectMapper jsonMapper = new ObjectMapper();
jsonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
jsonMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
Foo foo = new Foo();
foo.setId("id");
System.out.println("Do not serialize nulls");
System.out.println(jsonMapper.writeValueAsString(foo));
Map<String, Object> map = new LinkedHashMap<>();
map.put("key1", "val1");
map.put("key2", null);
System.out.println(jsonMapper.writeValueAsString(map));
}
}

Writing JSON arrays on multiple lines using Jackson in Java [duplicate]

I am using Jackson and would like to pretty-print JSON such that each element in arrays goes to each line, like:
{
"foo" : "bar",
"blah" : [
1,
2,
3
]
}
Setting SerializationFeature.INDENT_OUTPUT true only inserts newline characters for object fields, not array elements, printing the object in this way instead:
{
"foo" : "bar",
"blah" : [1, 2, 3]
}
Does anyone know how to achieve this? Thanks!
If you don't want to extend DefaultPrettyPrinter you can also just set the indentArraysWith property externally:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
String json = objectMapper.writer(prettyPrinter).writeValueAsString(object);
Thanks to the helpful hints, I was able to configure my ObjectMapper with desired indentation as follows:
private static class PrettyPrinter extends DefaultPrettyPrinter {
public static final PrettyPrinter instance = new PrettyPrinter();
public PrettyPrinter() {
_arrayIndenter = Lf2SpacesIndenter.instance;
}
}
private static class Factory extends JsonFactory {
#Override
protected JsonGenerator _createGenerator(Writer out, IOContext ctxt) throws IOException {
return super._createGenerator(out, ctxt).setPrettyPrinter(PrettyPrinter.instance);
}
}
{
ObjectMapper mapper = new ObjectMapper(new Factory());
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
}
You could extend the DefaultPrettyPrinter and override the methods beforeArrayValues(…) and writeArrayValueSeparator(…) to archieve the desired behaviour. Afterwards you have to add your new Implementation to your JsonGenerator via setPrettyPrinter(…).
Mapper can be configured (jackson-2.6) with:
ObjectMapper mapper = ...
DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
prettyPrinter.indentArraysWith(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
mapper.setDefaultPrettyPrinter(prettyPrinter);
//use mapper
The answer thankfully provided by OP shows a way for obtain a single-array-element-per-line formatted JSON String from writeValueAsString. Based on it here a solution to write the same formatted JSON directly to a file with writeValue with less code:
private static class PrettyPrinter extends DefaultPrettyPrinter {
public static final PrettyPrinter instance = new PrettyPrinter();
public PrettyPrinter() {
_arrayIndenter = Lf2SpacesIndenter.instance;
}
}
{
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer(PrettyPrinter.instance);
writer.writeValue(destFile, objectToSerialize);
}
try out JSON Generator...
API Reference
good example

Jackson serialization with including null values for Map

I've the following POJOs that I want to serialize using Jackson 2.9.x
static class MyData {
public Map<String, MyInnerData> members;
}
static class MyInnerData {
public Object parameters;
public boolean isPresent;
}
Now if I populate the data with the following sample code as shown:
Map<String, Object> nodeMap = new LinkedHashMap<>();
nodeMap.put("key-one", "val1");
nodeMap.put("key-null", null);
nodeMap.put("key-two", "val2");
Map<String, Object> child1 = new LinkedHashMap<>();
child1.put("c1", "v1");child1.put("c2", null);
nodeMap.put("list", child1);
MyInnerData innerData1 = new MyInnerData();
innerData1.parameters = nodeMap;
innerData1.isPresent = true;
MyData myData = new MyData();
myData.members = new LinkedHashMap<>();
myData.members.put("data1", innerData1);
// serialize the data
ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
String actual = mapper.writeValueAsString(myData);
System.out.println(actual);
This ends up printing
{"members":{"data1":{"parameters":{"key-one":"val1","key-two":"val2","list":{"c1":"v1"}},"isPresent":true}}}
Desired Output (same code gives correct output with Jackson 2.8.x )
{"members":{"data1":{"parameters":{"key-one":"val1","key-null":null,"key-two":"val2","list":{"c1":"v1","c2":null}},"isPresent":true}}}
If I remove the setSerializationInclusion(JsonInclude.Include.NON_NULL) on the mapper, I get the required output but the existing configuration for the ObjectMapper cant be changed. I can make changes to the POJO however.
What would be the least change to get the desired output?
You need to configure your object like this: mapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS);

Gson to json add map dynamically to object

I have an object that represents an event that I would like to serialize into json, using gson or another library if that works easier.
I want to add the following type of field to the json:
private Map<String, String> additionalProperties;
And also in another use case:
private Map<String, Object> additionalProperties;
But if I add additionalProperties to the Event object, and build Gson in the normal way:
Gson gson = BUILDER.create();
String json = gson.toJson(event);
It will appear like so:
additional_properties: {"value1":1,"value2":"abc"}
I would simply like to append to the event object in the following form:
{"value1":1,"value2":"abc"}
Here is an example output- the additional properties added are the object 'z' and the object 'advertiser':
{"organisationid":"2345612ß","projectid":"12345678",
"place":{"placeId":"2345","last_place":"123-3"},
"advertiser":{"advertiserId":"2345a","code":"a123-3"},
"user":{"isY":false,"isHere":false,"isBuyer":false},
"x":{"identifier":"SHDG-28CHD"},
"z":{"identifier":"abcSHDG-28CHD"},
"event_type":"x_depart"}
Here is what it currently looks like:
{"organisationid":"2345612ß","projectid":"12345678",
"place":{"placeId":"2345","last_place":"123-3"},
additionalproperty: {"advertiser":{"advertiserId":"2345a","code":"a123-3"},
"user":{"isY":false,"isHere":false,"isBuyer":false},
"x":{"identifier":"SHDG-28CHD"},
additionalproperty: {"z":{"identifier":"abcSHDG-28CHD"}},
"event_type":"x_depart"}
The best way to solve this would be with a framework for adding properties dynamically, but without this, you could add the additional properties to your Event object (include #JsonIgnore
so that it is not part of the final json), create a new JSONObject from the additional properties and merge it to the event JSONObject before serializing to json. This way the additional properties are added dynamically to the resulting Event output.
In the Event class:
#JsonIgnore
private Map<String, Object> additionalProperties;
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
}
A function to merge two JSONObjects:
public static JSONObject mergeObjects(JSONObject source, JSONObject target) throws JSONException {
for (String key: JSONObject.getNames(source)) {
Object value = source.get(key);
if (!target.has(key)) {
// new value for "key":
target.put(key, value);
} else {
// existing value for "key" - recursively deep merge:
if (value instanceof JSONObject) {
JSONObject valueJson = (JSONObject)value;
deepMerge(valueJson, target.getJSONObject(key));
} else {
target.put(key, value);
}
}
}
return target;
}
Putting the two objects together:
String jsonAdd = mapper.writeValueAsString(additional);
String jsonEvent = mapper.writeValueAsString(event);
JSONObject jsonAddObj = new JSONObject(jsonAdd);
JSONObject JsonEventObj = new JSONObject(jsonEvent);
JSONObject finalJson = Merge.deepMerge(jsonAddObj, JsonEventObj);
If your Event class is something like;
class Event {
private Map<String, Object> additionalProperties;
}
and you are calling;
String json = gson.toJson(event);
The ecpected and the valid output would be:
{"additionalProperties":{"value1":1,"value2":"abc"}}
If you want an output such as;
{"value1":1,"value2":"abc"}
You can call;
String json = gson.toJson(event.additionalProperties);
I would simply like to append to the event object in the following
form:
{"value1":1,"value2":"abc"}
That way it won't be a valid json variable if you append that value directly to a json object. You should better try if the json value you want is valid or not at http://jsonviewer.stack.hu/

How to wrap a List as top level element in JSON generated by Jackson

I am running into a problem where I am trying to include a List as the root node, but I can't seem to be able to get this. Let me explain. Let's say we have a class "TestClass"
class TestClass{
String propertyA;
}
Now, in some utility method this is what I do
String utilityMethod(){
List<TestClass> list = someService.getList();
new ObjectMapper().writeValueAsString(list);
}
The output I am trying to get in JSON is
{"ListOfTestClasses":[{"propertyA":"propertyAValue"},{"propertyA":"someOtherPropertyValue"}]}
I have tried to use
objMapper.getSerializationConfig().set(Feature.WRAP_ROOT_VALUE, true);
But, I still don't seem to get it right.
Right now, I am just creating a Map < String,TestClass > and I write that to achieve what I am trying to do, which works but clearly this is a hack. Could someone please help me with a more elegant solution? Thanks
Unfortunately, even with the WRAP_ROOT_VALUE feature enabled you still need extra logic to control the root name generated when serializing a Java collection (see this answer for details why). Which leaves you with the options of:
using a holder class to define the root name
using a map.
using a custom ObjectWriter
Here is some code illustrating the three different options:
public class TestClass {
private String propertyA;
// constructor/getters/setters
}
public class TestClassListHolder {
#JsonProperty("ListOfTestClasses")
private List<TestClass> data;
// constructor/getters/setters
}
public class TestHarness {
protected List<TestClass> getTestList() {
return Arrays.asList(new TestClass("propertyAValue"), new TestClass(
"someOtherPropertyValue"));
}
#Test
public void testSerializeTestClassListDirectly() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
System.out.println(mapper.writeValueAsString(getTestList()));
}
#Test
public void testSerializeTestClassListViaMap() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final Map<String, List<TestClass>> dataMap = new HashMap<String, List<TestClass>>(
4);
dataMap.put("ListOfTestClasses", getTestList());
System.out.println(mapper.writeValueAsString(dataMap));
}
#Test
public void testSerializeTestClassListViaHolder() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final TestClassListHolder holder = new TestClassListHolder();
holder.setData(getTestList());
System.out.println(mapper.writeValueAsString(holder));
}
#Test
public void testSerializeTestClassListViaWriter() throws Exception {
final ObjectMapper mapper = new ObjectMapper();
final ObjectWriter writer = mapper.writer().withRootName(
"ListOfTestClasses");
System.out.println(writer.writeValueAsString(getTestList()));
}
}
Output:
{"ArrayList":[{"propertyA":"propertyAValue"},{"propertyA":"someOtherPropertyValue"}]}
{"ListOfTestClasses":[{"propertyA":"propertyAValue"},{"propertyA":"someOtherPropertyValue"}]}
{"ListOfTestClasses":[{"propertyA":"propertyAValue"},{"propertyA":"someOtherPropertyValue"}]}
{"ListOfTestClasses":[{"propertyA":"propertyAValue"},{"propertyA":"someOtherPropertyValue"}]}
Using an ObjectWriter is very convenient - just bare in mind that all top level objects serialized with it will have the same root name. If thats not desirable then use a map or holder class instead.
I'd expect the basic idea to be something like:
class UtilityClass {
List listOfTestClasses;
UtilityClass(List tests) {
this.listOfTestClasses = tests;
}
}
String utilityMethod(){
List<TestClass> list = someService.getList();
UtilityClass wrapper = new UtilityClass(list);
new ObjectMapper().writeValueAsString(wrapper);
}

Categories

Resources