For example
public class HistoryRecordDeserializer implements JsonDeserializer<HistoryRecord> {
private LocalDateTimeConverter dateTimeConverter = new LocalDateTimeConverter();
#Override
public HistoryRecord deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
User user = new User();
user.setId(UUUID.fromString(json.get("user").get("id").getAsString()));
OtherData data = new OtherData();
data.setData(json.get("otherData").getAsLong());
return UserAndData(user, otherData);
}
As you can see, I instantiate User and OtherData manually, but I think there is a better solution. What is the best way to deserialize user with fromJson(...)? Should I pass Gson instance to HistoryRecordDeserializer? Should I create new one?
My problem was solved by using JsonDeserializationContext.
#Override
public HistoryRecord deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject object = json.getAsJsonObject();
JsonObject extras = object.get("extraData").getAsJsonObject();
HistoryRecord hr = object.context.deserialize(object.get("data"), HistoryRecord.class);
hr.appendExtraData(extras, HistoryRecordExtraData.class);
...
}
As #varren sad:
If you Gson can deserialize this, then context will be also able to do this.
So, you can even apply another custom type adapter(LocalDateTimeConverter):
gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeConverter())
.registerTypeHierarchyAdapter(HistoryRecord.class, new HistoryRecordDeserializer())
.create();
and use it inside HistoryRecordDeserializer:
LocalDateTime localDateTime = context.deserialize(object.get("dateTime"), LocalDateTime.class);
Related
I have a problem trying to deserialize a gson LocalDate.
I have the next 2 adaptors:
public class LocalDateSerializer implements JsonSerializer < LocalDate > {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d-MMM-yyyy");
#Override
public JsonElement serialize(LocalDate localDate, Type srcType, JsonSerializationContext context) {
return new JsonPrimitive(formatter.format(localDate));
}
}
and
public class LocalDateDeserializer implements JsonDeserializer < LocalDate > {
#Override
public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return LocalDate.parse(json.getAsString(),
DateTimeFormatter.ofPattern("d-MMM-yyyy").withLocale(Locale.ENGLISH));
}
}
I try to make a simple Serialization of an object "Task" which have a field starttime of LocalDate type.
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateSerializer());
gsonBuilder.registerTypeAdapter(LocalDate.class, new LocalDateDeserializer());
Gson gson = gsonBuilder.setPrettyPrinting().create();
LocalDate now=LocalDate.now();
Task task=new Task();
task.setID(1);
task.setDuration(2);
task.setID_Proiect(1);
task.setStarttime(now);
JSONObject json=new JSONObject(task);
String aux1=gson.toJson(json);
System.out.println(aux1);
Task t2=gson.fromJson(aux1,Task.class);
I receive the error
Failed making field 'java.time.LocalDateTime#date' accessible; either
change its visibility or write a custom TypeAdapter for its declaring
type
Can you tell me what is wrong with this code? I know it is probably a noobie question but i rly need help to improve my skills. Ty
I have created a deserialization, that whenever it see the String "nil", it will return null.
private static Gson createCustomGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(String.class, new JsonDeserializer<String>() {
#Override
public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
return (json.getAsString().equals("nil")) ? null : json.getAsString();
}
});
return gsonBuilder.create();
}
It works good except that, I want to add an exception where for the field "Keyword" that store a List, I don't want to eliminate nil to return null, but retain the String. How to add the exception for "Keyword"?
My Keyword class is of the below type
public class KeywordListing implements Serializable {
List<String> keys;
}
Found a solution. It's by adding another TypeAdapter to use back the default deserizliation from Gson instead as below.
private static Gson createCustomGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(String.class, new JsonDeserializer<String>() {
#Override
public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
return (json.getAsString().equals("nil")) ? null : json.getAsString();
}
});
gsonBuilder.registerTypeAdapter(KeywordListing.class, new JsonDeserializer< KeywordListing >() {
#Override
public KeywordListing deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
return new Gson().fromJson(json, KeywordListing.class);
}
});
return gsonBuilder.create();
}
Let me know if there's a shorter answer than what I got above.
is there any easy way to to convert this json:
{
...,
"pictures": [
"url1",
"url2"
],
...
}
to
List<Picture> pictures
where Picture is:
class Picture{
String url;
}
It won't work as above, because I have an exception, saying
Expected BEGIN_OBJECT but was STRING
You need to implement a custom deserializer for this.
Should be looking like this (I didn't try to execute, but that should give you the idea where to start, presumably you have a public constructor with String argument in your Picture.class)
private class PictureDeserializer implements JsonDeserializer<Picture> {
public Picture deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new Picture(json.getAsJsonPrimitive().getAsString());
}
}
It should be registered:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Picture.class, new PictureDeserializer());
I have one class User, I received JSON (for User class) from system1 and I should read info , validate then forward to system2, I can't touch these 2 systems, the problem is the names of keys are different, I want to differentiate between deserialized and serialized name
received JSON is :
{"userId":"user1","pwd":"123456","country":"US"}
"{"username":"user1","password":"123456","country":"US"}"
But the sent should be like this
I am using Gson lib, and this is my code:
User class:
class User implements Cloneable {
#SerializedName("username")
private String username ;
#SerializedName("password")
private String password ;
#SerializedName("country")
private String country ;
}
TestJson class
class TestJson {
private static GsonBuilder gsonBuilder;
private static Gson gson;
public static Object fromJson(String json, Class clz) {
gson = new Gson();
return gson.fromJson(json, clz);
}
public static String toJson(Object obj) {
gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
String json = gson.toJson(obj);
return json;
}
public static void main(String[] args) {
String json2 = "{\"userId\":\"user1\",\"pwd\":\"123456\",\"country\":\"US\"}";
User user = (User) TestJson.fromJson(json2, User.class);
System.out.println(user.getPassword());
User u = new User("user1","123456","US");
String json1 = TestJson.toJson(u);
System.out.println(json1);
}
}
If there are alternative names of field just use alternate param of #SerializedName
public class User {
#SerializedName(value="username", alternate={"userId", "useriD"})
private String username ;
...
}
You can create custom serializer/deserializer for this purpose.
Serializer:
public class UserSerializer implements JsonSerializer<User> {
#Override public JsonElement serialize(User obj, Type type, JsonSerializationContext jsonSerializationContext) {
..........
}
}
Deserializer:
public class UserDeserializer implements JsonDeserializer<User> {
#Override public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
...........
}
}
and to create Gson instance:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(User.class, new UserSerializer());
gsonBuilder.registerTypeAdapter(User.class, new UserDeserializer());
Gson gson = gsonBuilder.create();
Example
Edit: this is an example of a custom deserializer which might fit into your need. We don't need a custom serializer in this case.
Add this UserDeserializer.java:
public class UserDeserializer implements JsonDeserializer<User> {
#Override
public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
User user = new User(obj.get("userId").getAsString(), obj.get("pwd").getAsString(), obj.get("country").getAsString());
return user;
}
}
Replace your fromJson implementation with this (I use generic to avoid the need for casting when calling fromJson):
public static <T> T fromJson(String json, Class<T> clz) {
gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(User.class, new UserDeserializer());
gson = gsonBuilder.create();
return gson.fromJson(json, clz);
}
The only way I can think of would be to have a custom Adapter or deser to a JsonObject and then map it to your User.
With Genson you can create two instances of Genson, one for deserialization and another one for serializaiton. The one used in deserialization could be configured with renamed properties like that.
// you can also precise that you want to rename only the properties from User class
Genson genson = new GensonBuilder()
.rename("username", "userId")
.rename("password", "pwd")
.create();
User user = genson.deserialize(json, User.class);
I have a json response that looks like this:
{
"id":"001",
"name":"Name",
"param_distance":"10",
"param_sampling":"2"
}
And I have two classes: Teste and Parameters
public class Test {
private int id;
private String name;
private Parameters params;
}
public class Parameters {
private double distance;
private int sampling;
}
My question is: is there a way to make Gson understand that some of the json attributes should go to the Parameters class, or the only way is to "manually" parse this ?
EDIT
Well, just to make my comment in #MikO's answer more readable:
I'll add a list of an object to the json output, so json response should look like this:
{
"id":"001",
"name":"Name",
"param_distance":"10",
"param_sampling":"2",
"events":[
{
"id":"01",
"value":"22.5"
},
{
"id":"02",
"value":"31.0"
}
]
}
And the Deserializer class would look like this:
public class TestDeserializer implements JsonDeserializer<Test> {
#Override
public Test deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
Test test = new Test();
test.setId(obj.get("id").getAsInt());
test.setName(obj.get("name").getAsString());
Parameters params = new Parameters();
params.setDistance(obj.get("param_distance").getAsDouble());
params.setSampling(obj.get("param_sampling").getAsInt());
test.setParameters(params);
Gson eventGson = new Gson();
Type eventsType = new TypeToken<List<Event>>(){}.getType();
List<Event> eventList = eventGson.fromJson(obj.get("events"), eventsType);
test.setEvents(eventList);
return test;
}
}
And doing:
GsonBuilder gBuilder = new GsonBuilder();
gBuilder.registerTypeAdapter(Test.class, new TestDeserializer());
Gson gson = gBuilder.create();
Test test = gson.fromJson(reader, Test.class);
Gives me the test object the way I wanted.
The way to make Gson understand it is to write a custom deserializer by creating a TypeAdapter for your Test class. You can find information in Gson's User Guide. It is not exactly a manual parsing, but it is not that different, since you have to tell Gson how to deal with each JSON value...
It should be something like this:
private class TestDeserializer implements JsonDeserializer<Test> {
public Test deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject obj = json.getAsJsonObject();
int id = obj.get("id").getAsInt();
String name = obj.get("name").getAsString();
double distance = obj.get("param_distance").getAsDouble();
int sampling = obj.get("param_sampling").getAsInt();
//assuming you have suitable constructors...
Test test = new Test(id, name, new Parameters(distance, sampling));
return test;
}
}
Then you have to register the TypeAdapter with:
GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Test.class, new TestDeserializer());
And finally you just have to parse your JSON as usual, with:
gson.fromJson(yourJsonString, Test.class);
Gson will automatically use your custom deserializer to parse your JSON into your Test class.