square / retrofit

A type-safe HTTP client for Android and the JVM
https://square.github.io/retrofit/
Apache License 2.0
43.03k stars 7.3k forks source link

How can I add convertor to retrofit 2.0 with a generic gson? #1740

Closed yy197133 closed 8 years ago

yy197133 commented 8 years ago

my server json like this: {code: msg: data:{} }

in POJO, data is generic (private T data;),I know how to parse,but I don't know how to add gson convertor to retrofit2.0?

artshell commented 8 years ago

Read the official document

[]()http://square.github.io/retrofit/

CONVERTERS

By default, Retrofit can only deserialize HTTP bodies into OkHttp's ResponseBody type and it can only accept its RequestBody type for @Body.

Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.

Gson: com.squareup.retrofit2:converter-gson Jackson: com.squareup.retrofit2:converter-jackson Moshi: com.squareup.retrofit2:converter-moshi Protobuf: com.squareup.retrofit2:converter-protobuf Wire: com.squareup.retrofit2:converter-wire Simple XML: com.squareup.retrofit2:converter-simplexml Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

About Serializing and Deserializing Generic Types:

Assumed, Serializing and Deserializing json data with Gson https://github.com/google/gson/blob/master/UserGuide.md#TOC-Serializing-and-Deserializing-Generic-Types

avenwu commented 8 years ago

@yy197133 It seams that you are not reading the retrofit document carefully. Always look at the official document/example before ask any questions;

I don't know how to add gson convertor to retrofit2.0?

Use com.squareup.retrofit2:converter-gson mentioned above;

data is generic (private T data;)

Data is absolutely ok to be different for each API response, it‘s nothing to do with generic, you'd better specify the detail data structure for each response. You can define base response class with data to be generic

JakeWharton commented 8 years ago

Seems like this was answered. Additionally there's a samples/ folder which has some example usages that include Gson. Feel free to direct specific questions to StackOverflow with the 'retrofit' tag in the future.