why addConverterFactory is need in Retrofit - java

My question is around Retrofit and GSON. I know GSON is used for JAVA object <-> JSON . I know that Retrofit parses our response. What i don't understand is why we need GsonConverterFactory .Also why is addConverterFactory needed in retrofit

UPDATE:
Pojo objects in Kotlin are data classes and annotation use is as in Java
ANSWER:
If your application is Restful, so gets and sends data from / to server
Converter factory need to be added, just for retrofit can convert JSON data (got from server) into java (model) objects (POJO), to use in Android Project.
There are some converter libraries for converting JSON to Java objects,
(GSON, Jackson..etc) you have to decide which converter you want to use in your project and add same factory
Dependencies in app.gradle
implementation "com.squareup.retrofit2:converter-gson:VERSION"
and Factories in Retrofit settings
GsonConverterFactory or JacksonConverterFactory
Retrofit.Builder().addConverterFactory(GsonConverterFactory.create());
Also if the remote data type is XML, you need to add SimpleXmlConverterFactory

if the json converters don't meet your needs you'll need to Add a customized converter factory for serialization and deserialization of your objects. consider this case.
i wish you'll find this article helpful.

The world is not just json and gson. There are other formats that you can use to implement Rest Apis, i.e. XML.
Also, in the world of json parsers there's not only gson but way more like Jackson and Moshi.
It would be extremely difficult to maintain all possible format converters inside Retrofit, so it offloads the parsing to classes that implement the interface for a converter. Putting this behind a factory lets Retrofit decouple even the creation of these converters, so it can have different ones for different responses and requests.
This also allows you to have multiple converters within the same Retrofit instance and it's also an easy way to let you implement your own converter.
All in all, this decoupling allows for way more flexibility than coupling it with specific libraries.

If you are using Spring, you should create a mapper configuration (or use a default, like in this example), in the retrofit configuration, you should att this code:
#Bean
fun retrofitBuilder(): Retrofit.Builder {
return Retrofit.Builder()
.addConverterFactory(JacksonConverterFactory.create(ObjectMapper()))
}
Then, in your application could read and write Kotlin data class Json, even with no # information.

Related

Jackson's #JsonAppend with default value

guys! I am developing a web application and I decided to use Jackson as my JSON processing framework.
In request data that I am willing to send; let's say the POJO looks like this:
data class JSONEnvelope(
#JsonProperty("obj1")
val obj1: Obj1,
#JsonProperty("obj2")
val obj2: Obj2)
which get serialized like this:
{
"obj1":{...},
"obj2":{...}
}
but I need to add some metadata to that object, let's say fields meta1 and meta. I thought that #JsonAppend would solve my problem, but I am using Jackson together with Jersey, so I am not serializing objects manually, so I cannot use writer.withAttribute("...", ...).
I am aware of this thread, but there is no answer that kinda satisfy my needs, because I think, that writing a custom serializer is a bit overkill for this, moreover if I do not have a mechanism to "serialize the rest of the original object". I'd be glad for any ideas
The solution in the answer you cited, which adds a mixIn to a the ObjectMapper then uses the ObjectWriter to configure it, is a good solution.
For Jersey, which calls ObjectMapper.writerFor and therefore prevents you from calling withAttribute in order to configure the ObjectWriter, one alternative is to add the attribute to the ObjectWriter before returning it from writerFor. I suggest subclassing ObjectMapper and overriding the various writerFor methods, adding the necessary attribute at that point. You can then get Jersey to use that ObjectMapper by registering it as a JAX-RS Provider: see the various annotations in javax.ws.rs to get started on this. This answer gives an example of what to do.

How is javax.ws.rs.client.Entity serializing objects to json?

What serializer is Entity.json(T entity) using to serialize/deserialize objects? Is it somehow possible to use a custom serializer?
In my case the serialization is wrong because my object contains fields with the Guava Optional data type and absent values are returned as {"present":false} instead of null.
The JSON serializer isn't specified by JAX-RS, it depends on your configuration. For example, Jersey JAX-RS allows several (https://jersey.java.net/documentation/latest/media.html), including
MOXy
Java API for JSON Processing (JSON-P)
Jackson
Jettison
But a better solution is not to use Optional (either Guava or Java 8) for fields. See http://blog.joda.org/2014/11/optional-in-java-se-8.html
My only fear is that Optional will be overused. Please focus on using
it as a return type (from methods that perform some useful piece of
functionality) Please don't use it as the field of a Java-Bean.
Not directly solving your problem. I suggest you use Googles Gson as a parser. It is very flexible and configurable.
Tutorial
It also skips blank fields so the json size is not too large.

Adding hypermedia for resource JSON representation using Jackson

I am generating my restful resource JSON representation using jackson and it works very well as far as standard property conversion is concerned. However I would also like to generate a bunch of hypermedia in the same json object for which i need to use uriinfo from jersey. Is there a way to pass uriinfo to jackson somehow and use a custom parser to use the uriinfo to generate hypermedia.
jackson version 2.x
You might want to take a look at jersey-linking. It basically uses annotations to generate URIs for you.

Is there a good "standard" Java interface for XML and JSON readers/writers?

Basically, I want to have an interface for converting Objects to/from their XML or JSON String representation, something like
public interface IStringifier{
/**
Converts the Object to it's String representation, e.g. XML or JSON
*/
public String toString(Object o);
/**
Converts from the String representation (e.g. XML or JSON) to an Object
*/
public Object fromString(String s, Class<?> clazz);
}
Such an interface would be fairly simple to implement in GSON, XStream etc. but by abstracting it you are abstracted from knowing just what is going on underneath. And you are decoupled from one of the many many XML or JSON libraries, so clients are freer to pick their favorite.
Is there any "standard" Java interface for this? Something in Guava, Apache, etc?
(added) None of the answers were what I really wanted ("yes, in javax.obscure.interfaces there's what you want") but thanks for the replies. I'll accept Tom's answer as the most informative/provocative. And maybe I'll clean up the code I have and try to create a standard. :-)
JAXB (JSR-222) is the Java SE/EE standard for converting objects to/from XML. It can be used standalone and is the standard binding layer for JAX-WS (SOAP) and JAX-RS (RESTful) Web Services. Below is a link to an example of specifying an alternate provider via a jaxb.properties file.
http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
There currently isn't a standard API for JSON binding.
I think you're overthinking this. You don't actually care about turning objects into Strings, you want to be able to serialize objects to different formats without knowing what that format is. But who says that different format is a String? What happens when you want your object to be available as a protocol buffer? That's a binary format, not a character format -- so stringify() won't help there. Ultimately, it's up to you to architect your application to be as independent as possible of those details.
XML and JSON are unrelated, so this is actually two questions:
For JSON, although "unofficial", a popular library is GSON.
For XML, see Blaise's answer
One popular JSON-to-Java binding library is Jackson
One popular XML-to-Java binding library is XStream
If you intend to use this in a web application, maybe you would like to consider Spring 3 MVC's facilities for this. Through annotations it does the conversion automatically and you can tell it whether you want XML or JSON (or various other formats). This might be the common interface you are looking for too.

Corss-Platform JSON stereotyping / Serializer reacting on type-attribute? (Java/Objective-C)

We've gotten a .NET project and want to serialize and deserialize JSON in .NET, Java and Objective-C. Unfortunately, we've got the following situation: one attribute in the data model maps to 4 other classes that all inherit from the same base class. Hence, when receiving the not-stereotyped JSON format, we don't know which type to serialize one of these 4 objects to.
As a solution, we want to integrate a "type"-attribute, telling the serializer which class to serialize the object to. JSON.NET actually supports this: http://json.codeplex.com/discussions/56031
We're now looking for experiences of other developers with serializers/deserializers on the Java and Objective-C platform. Is there any chance to modify these serializers in a way that it reacts on the type-attribute?
Gson for java support it too. I have same problem and solve it with custom serializer/deserialized. All you have to do: implements your serializer/deserializer and register it in GsonBuilder. Read about it here.

Categories