Jackson exception on writeValueAsString method - java

I am trying to integrate Jackson on my java code to convert object to Json and back. My project is a web application developed in for Tomcat7 and Java7. I just downloaded the last version (2.6.0) jars of Jackson and was trying to do convert an object to json.
String outJson ="";
myobject p = new myobject ();
ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
try {
outJson = mapper.writeValueAsString(p);
} catch (Exception e) {
out.println(e.toString());
}
When I run this, I get an exception like this:
com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException)
I have done the oposite way, converting from json to the object and the result was ok.
After some research I found some references to posible dependency problem, but I can not find what I am missing. I have included the following jars, obtained from Maven repository:
jackson-annotations-2.6.0.jar
jackson-core-2.6.0.jar
jackson-databind-2.6.0.jar
jackson-dataformat-smile-2.6.0.jar
jackson-jaxrs-json-provider-2.6.0.jar
jackson-module-jaxb-annotations-2.6.0.jar
Any ideas of what could be the problem?

As said in the comments the problem was that I was not initializing correctly the object. As there was no data, I got the NullPointerException.

Related

UnsupportedOperationException was thrown when serializing a Throwable variable using XStream

When I tried using XStream 1.4.9 to serialize an IllegalArgumentException type variable, there is a java.lang.UnsupportedOperationException.
Below is the stack trace information.
I have no idea what this could mean. Information from online is limited.
java.lang.UnsupportedOperationException: Not supported. Pass in the cause using the constructors instead.
at com.oracle.truffle.api.exception.AbstractTruffleException.initCause(AbstractTruffleException.java:413)
at com.thoughtworks.xstream.converters.extended.ThrowableConverter.marshal(ThrowableConverter.java:56)
at com.thoughtworks.xstream.core.AbstractReferenceMarshaller.convert(AbstractReferenceMarshaller.java:68)
try {
final ScriptEngine scriptEngine = new ScriptEngineManager()
.getEngineByName("JavaScript");
Objects.toString(scriptEngine.eval("X"), null);
} catch (Exception e) {
XStream xstream = new XStream();
System.err.println(xstream.toXML(e));
}
This is a minimum example that I see.
I realize that whenever I used js-scriptengine dependency, XStream fails to serialize it, while removing such dependency, everything works
I think it's due to Graalvm's implementation of "javax.script.ScriptEngine" class, which are not implemented as what jdk has implemented.
Removing Graalvm dependency, everything works fine.

jackson.databind.ObjectMapper upperCasing json Array and Object names

I am trying to use JMSTemplate to publish a JSON message to a topic. This code already existed in one application and I was simply copying it to another as we are trying to consolidate two applications into one. I have found that the code is now sending JSON messages that have the first letter capitalized for the JSONArray and JSONObject field names.
I was using JMS template with a message converter that takes in an object mapper to convert from a POJO to a JSON. The only real difference in my new code is that I am using a newer version of spring boot. I know this would update all of the jackson dependencies so maybe that is why this change has occurred. I ended up trying to set the naming strategy on my object mapper but this doesn't seem to work. I originally did it in my bean definition but in order to see if it was actually working I tried it before I did a convertAndSend, and it did not work. I was still getting uppercase JSON Object and Array names.
public void sendMessage(Object responseToSend) {
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);// does not seem to make a difference
try {
System.out.println(objectMapper.writeValueAsString(responseToSend));//prints array and object names with the first letter capitolized
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jmsTemplatePublish.convertAndSend("REDACTED",
responseToSend);
}
So, For example, my new application is sending something like.
"Quote":[{"QuoteInformation":{"Inputs":{"exampleField":false,"ExampleWritten":{"dwelling":true}}
where before it was like this
"quote":[{"quoteInformation":{"inputs":{"exampleField":false,"exampleWritten":{"dwelling":true}}
#Kachopsticks did you tried that PropertyNamingStrategy.LOWER_CASE in objectMapper namingStrategy configs instead of using PropertyNamingStrategy.LOWER_CAMEL_CASE.
This bean was the culprit. Had to remove .modulesToInstall(JaxbAnnotationModule.class);
#SuppressWarnings("unchecked")
#Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
return Jackson2ObjectMapperBuilder.json()
.serializationInclusion(JsonInclude.Include.NON_EMPTY)
.defaultViewInclusion(true)
.modulesToInstall(JaxbAnnotationModule.class);
}

Gson fromJson returning empty JsonObject

So, I've got a String that is the result of a toJson method I've implemented on a class, and have confirmed in my test code that it is the correct Json representation of my class. My goal is to turn this String into a JsonObject and pass it to a constructor, using Gson. However, I'm running into an odd problem.
This is the code I'm calling:
Gson gson = new Gson();
JsonObject jObj = gson.fromJson(jsonString, JsonObject.class);
I have used literally this exact same snippet of code before in many places in my project, for other classes, and it has worked fine. I even copied one of those functional snippets of code into this test class and tried it. However, every version I try results in the same thing--jObj is an empty set of brackets.
I don't understand how it's happening. I've confirmed that jsonString has all the fields it should need. Why is Gson returning an empty JsonObject? No exceptions are being thrown.
Ok so i know this is a little old but I had the same exact issue. The resolution was changing the jar file. I had a similar code sample working in another project but then I was experiencing the exact same problem in another. Well the problem was an older gson-2.1.jar. Updated the problem application to the matching gson-2.3.1.jar and all was working. Hope this helps.
From your comment that says the string is {"varName":1, "otherVarName":2, "thirdVarName":3.4}, looks like the serialized object was a Map. You may need to specify the type token:
gson.fromJson(jsonString, new TypeToken<Map<K,V>>() {}.getType());
where K and V are the key and value types of the map. If it is not a Map, specify whatever class the jsonString was obtained from.
For my case, I was accidentally using the following initializer in my dagger module.
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
I removed the setFieldNamingPolicy and it worked.
I had this issue as well.
I was using
return gson.fromJson(response, JsonObject::class.java)
And I was receiving an object with only the default values populated.
I had to explicitly define the serialized names for each property in my JsonObject class that was different from how it was named in the json response.
For example, if in the json I was parsing the field name was "total_score', but my JsonObject had a field named "totalProperty", I had to use the #SerialedName annotation to define the relationship.
#SerializedName("total_score")
val TotalScore : Int = 0

how can an object be not json serializable?

private FbDataToServer generateFbDataToServer(
GraphObject graphObject) {
Gson gson = new Gson();
FbDataToServer fbDataToServer = new FbDataToServer();
ֿ fbDataToServer.fbJson = gson.toJson(graphObject
.getInnerJSONObject());
Everytime I try to parse FB graphObject object to Json -
an error is thrown.
How can it be? how can an object be not json serializable?
The error said the object is not serializable.
I'll try to get reproduce the error again.
Actually, i have never use the facebook API. But when it comes to serialize the object to json string, i recommend you that fastjson is much better.
https://github.com/alibaba/fastjson
Fastjson is the fastest processing library in java (even than jackson, let alone gson) and it has no special requirements to the object ,just be the pain java bean is enough.
By the way, fastjson is developed by Chinese, so its documentation are mainly in Chinese. If you have trouble with its api, you can contact with me.

Serialize an object to json in Java?

I am trying to serialize an instance of Campaign in Adwords API with gson at first with the code below:
Campaign c = new Campaign();
c.setName("beijing");
c.setId(23423L);
Gson gson = new Gson();
String json = gson.toJson(c);
and I get the exception that class Money declares multiple JSON fields named __equalsCalc. When I try to serialize the instance with json plugin of struts2 with the code below
String str = org.apache.struts2.json.JSONUtil.serialize(c);
System.out.println(str);
It works and output the correct result
{"adServingOptimizationStatus":null,"biddingStrategy":null,"budget":null,"campaignStats":null,"conversionOptimizerEligibility":null,"endDate":null,"frequencyCap":null,"id":23423,"name":"beijing","networkSetting":null,"servingStatus":null,"settings":null,"startDate":null,"status":null}
Then my question is that why can the json plugin of struts2 can serialize the instance correctly while gson cannot? Can I use the json plugin of struts2 to serialize objects to json since it is design to produce json result in struts2 not for this situation.
You can use the json plugin in struts2 to serialize your object manually to json string. You can do that by calling the serialize static method.
String jsonString = JSONUtil.serialize(your_object);
Don't forget to include xwork-core jar in your classpath because it depends on it.
Sounds like either a bug in Gson or it is more particular/less robust. Without looking at the code for either it would be hard to know more.
Personally I use Jackson for JSON to POJO transformations.
Ultimately as long as the Structs2 plugin is available on your classpath I don't see why you couldn't leverage it's classes to handle JSON transformations. Ultimately JSON is a format therefore all JSON libraries need to produce commonly understandable data.
I had a similar problem and solved it by moving my use of SimpleDateFormat from the class level to inside a method. GSON doesn't have to serialize SimpleDateFormat this way.
Hope this helps someone - 45 minutes of head banging for me! :-)

Categories