My webservice is giving me this format of Date: 1462575665220.
How can I deserialize this using GSON?
I think that I have to use something like this:
new GsonBuilder().setDateFormat("dd-MM-yyyy HH:mm:ss").create();
But I dont know what kind of format is it.
Can I deserialize it or I have to change something in the Webservice?
Sorry for bad english, I hope you understand.
Try this:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = builder.create();
Related
i have get response like this
Array (
[status] => 9
[message] => Your devices not verify!
)
i use this code but not read response Html.fromHtml(jsonString).toString()
so,how can read this in android or json object format?
i also use
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
Post pst;
pst = gson.fromJson(jsonString, Post.class);
Post.class
class Post
{
String message;
String status;
}
I'm trying to create a dynamic response based converter
using retrofit, As for now I have 2 different answers returning from the server - one represents a failure and one represent a valid response How can I try and parse two different objects using the same adapter\callabck?
You can parse it as a java bean if data are json data.
You can use Gson to parse it.
1 Add lib
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.google.code.gson:gson:2.7'
2 Create Retrofit
private Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Api.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Just add a Gson converter.
For example,
// success
{"retcode":0,"result":{"vfwebqq":"xxxx"}}
// failed
{"retcode":100,"result":{}}
3 Create a bean to receive data.
public class Result {
public String retcode;
public Info result;
public static class Info {
public String vfwebqq;
}
}
4 Then you can return a bean object in retrofit interface.
#GET("xxx")
Result getHome();
Actually I'm not quite in what are you talking about and what exact issue you are facing. But the first thing that pops out of my head is just to provide custom JsonDeserializer. It should look like smth like this :
public class CustomDeserializer implements JsonDeserializer<List<CustomData>> {
#Override
public List<CustomData> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
List<CustomData> customDataSet = new ArrayList<>();
Iterator<JsonElement> iterator = ((JsonObject) json).get("data").getAsJsonObject().get(
"records").getAsJsonArray().iterator();
while (iterator.hasNext()) {
JsonElement element = iterator.next();
CustomData customData = ServiceGenerator.mGson.fromJson(element, CustomData.class);
customDataSet.add(customData);
}
return customDataSet;
}
}
That's just a custom parser class example which is applied to RetrofitBuilder just to make life easier(maybe).
Afterwards you need to :
Type listType = new TypeToken<List<CustomData>>() {
}.getType();
mGson = new GsonBuilder().registerTypeAdapter(listType, new CustomDeserializer()).create();
builder =
new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(mGson))
.baseUrl(API_BASE_URL);
retrofit = builder.build();
Based on your question, i believe this site helps with your challenge:
https://futurestud.io/tutorials/retrofit-2-introduction-to-multiple-converters
I have a WCF Service that returns a List of objects to an Android app. One of the properties is a DateTime property. The return format is JSON and I am getting the date in this format /Date(1441117247253+0200)/ on the Android side. I am using com.squareup.retrofit:retrofit:1.9.0 to get the data from my service.
I have no clue how to use Retrofit to create a the string date into a Date object. I had a look at this http://square.github.io/retrofit/ under the Custom Converters section, but do not know how to go further. This is what I've tried but I do not know how to implement the converter class.
creating the restAdapter like so:
restAdapter = new RestAdapter.Builder()
.setConverter(new DotNetDateConverter())
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(API).build();
and the DotNetDateConverter Class which I do not know how to implement further:
public class DotNetDateConverter implements Converter
{
#Override
public Object fromBody(TypedInput body, Type type) throws ConversionException
{
return null;
}
#Override
public TypedOutput toBody(Object object)
{
return null;
}
}
there are other fields in the response which are fine, but how do I change the /Date(1441117247253+0200)/ to a proper java.util.Date object? Without the converter I get com.google.gson.JsonSyntaxException:/Date(1441117247253+0200)/ obviously because the string cannot be converter to a date.
Any assistance would greatly be appreciated.
Ok, so after some digging around, I came across this. My approach was wrong. So I ended up creating a Converter like this:
public class DotNetDateConverter implements JsonDeserializer<Date>
{
#Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
String s = json.getAsJsonPrimitive().getAsString();
long l = Long.parseLong(s.substring(s.indexOf("(")+1, s.indexOf("+")));
Date d = new Date(l);
return d;
}
}
I also had to register it like so:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DotNetDateConverter());
restAdapter = new RestAdapter.Builder()
.setConverter(new GsonConverter(gsonBuilder.create()))
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(API).build();
I had to change the code a bit to accommodate my specific scenario, that being dates come in as /Date(1441117247253+0200)/ with the time zone. Maybe someone else might find some use for this...
I'm using Google GSON library in my android app to parse json response from server.
In some cases API retrieve html codes in response (e.g »). Is it possible to tell Google GSON to parse that codes and convert to symbol that associated with that code?
Gson does not have anything built in that would do that, no.
The only way to have Gson do this for you would be to write a custom deserializer for String that would decode the strings. You'd also need another library to do the HTML decoding since Java itself doesn't include anything.
Here's an example using the Apache Commons Lang library to do the decoding:
public class App
{
String foo;
public static void main(String[] args) throws MalformedURLException, IOException
{
String json = "{\"Text\":\"«Some message»\"}";
Gson g =
new GsonBuilder()
.registerTypeAdapter(String.class, new MyStringDeserializer()).create();
Type t = new TypeToken<Map<String,String>>(){}.getType();
Map<String,String> map = g.fromJson(json, t);
System.out.println(map.get("Text"));
}
}
class MyStringDeserializer implements JsonDeserializer<String>
{
#Override
public String deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException
{
String s = StringEscapeUtils.unescapeHtml3(je.getAsString());
return s;
}
}
Output:
«Some message»
I want to change rules for Gson parser (json parser wrote by google for Android). For example I have the object of class:
enum Type
{
PRIMARY,
SECONDARY
}
class A
{
public int i = 4;
public Type type = Type.PRIMARY;
}
A a = new A();
Now if I will convert that object via Gson converter:
Gson gson = new Gson();
JsonElement json = gson.toJson(a);
I will get that json element: {"i":4,"type":"PRIMARY"}. Instead of this I want to get: {"i":4,"type":0}, i.e. ordinal of type instead of a name of it.
How can I do that?
Tnx.
Ok, I found the answer:
For doing that need to create Gson object from GsonBuilder. But before that register a new type hierarchy adapter for gson builder for Enum.class type with your own json serializer that will do the work.
// new Json serializer for Enum<?> class
class ObjectTypeSerializer implements JsonSerializer<Enum<?>>
{
private static final JsonParser mParser = new JsonParser();
public JsonElement serialize(Enum<?> object_,
Type type_,
JsonSerializationContext context_)
{
// that will convert enum object to its ordinal value and convert it to json element
return mParser.parse(((Integer)object_.ordinal()).toString());
}
}
// creation of gson builder
GsonBuilder gsonBuilder = new GsonBuilder();
// registration of type hierarchy adapter
gsonBuilder.registerTypeHierarchyAdapter(Enum.class, new ObjectTypeSerializer());
// creation gson from builder
Gson gson = gsonBuilder.create();
Now gson will do the work!