when deserializing a json into a class Foo{int id; List<String> items; List<Long> dates;} How could I auto initialize fields that are null after deserialization. Is there such a possiblity with Gson lib?
ex:
Foo foo = new Gson().fromJson("{\"id\":\"test\", \"items\":[1234, 1235, 1336]}", Foo.class)
foo.dates.size(); -> 0 and not null pointerException
I know I could do if (foo.attr == null) foo.attr = ...
but I'm looking for more generic code, without knowledge of Foo class
thx
edit: sorry just putting Getters in Foo is enough
closed
You need to create your custom deserializer.
Assuming your class is called MyAwesomeClass, you implement something like
MyAwesomeClassDeserializer implements JsonDeserializer<MyAwesomeClass> {
#Override
public MyAwesomeClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) throws JsonParseException
{
// TODO: Do your null-magic here
}
and register it with GSON, like this:
Gson gson = new GsonBuilder()
.registerTypeAdapter(MyAwesomeClass.class, new MyAwesomeClassDeserializer())
.create();
Now, you just call a fromJson(String, TypeToken) method, to get your deserialized object.
MyAweSomeClass instance = gson.fromJson(json, new TypeToken<MyAwesomeClass>(){}.getType());
Related
I have overriden an Integer Adapter in GSON to parse my JSON. Reason for doing this is that the GSON method parseJson simply throws the JsonSyntaxException if anything goes wrong. To avoid sending a generic exception I created this adapter. I want the adapter to throw an exception along with the name of the Key. Problem is that I can not get the key name in the overriden method deserialize of JsonDeserializer[T]
Code snippet
val integerAdapter = new JsonDeserializer[Integer] {
override def deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Integer = {
Try(json.getAsInt) //JsonElement object has only the value
match {
case Success(value) => value
case Failure(ex) => throw new IllegalArgumentException(ex) // here i want the name of the key to be thrown in the exception and manage accordingly
}
}
}
Json:{
"supplierId":"21312",
"isClose":false,
"currency":"USD",
"statusKey":1001,
"statusValue":"Opened ",
"statusDateTime":"2014-03-10T18:46:40.000Z",
"productKey":2001,
"productValue":"Trip Cancellation",
"TypeKey":3001,
"TypeValue":"Trip Cancellation",
"SubmitChannelKey":4001,
"SubmitChannelValue":"Web asdsad",
"tripNumber":"01239231912",
"ExpiryDateTime":"2014-03-10T18:46:40.000Z",
"numberOfants":4,
"AmountReserved":901232,
"AmountRequested":91232
}
Any leads on this?
Your adapter is a deserializer for the Integer type which is a wrapper for a primitive. Because it's not a regular object, Gson will not associate a key with it.
Why not implement a deserializer for the whole JSON object to have access to all keys?
class MyObject {
private Integer supplierId;
private boolean isClose;
// TODO: the other fields in the JSON string
}
class MyObjectDeserializer implements JsonDeserializer<MyObject> {
public MyObject deserialize(JsonElement jsonElement, Type type,
JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
// TODO: construct a new MyObject instance
}
}
I need to deserialize a Json file that has an array. I know how to deserialize it so that I get a List object, but in the framework I am using a custom list object that does not implement the Java List interface. My question is, how do I write a deserializer for my custom list object?
EDIT: I want the deserializer to be universal, meaning that I want it ot work for every kind of list, like CustomList<Integer>, CustomList<String>, CustomList<CustomModel> not just a specific kind of list since it would be annoying to make deserializer for every kind I use.
This is what I came up with:
class CustomListConverter implements JsonDeserializer<CustomList<?>> {
public CustomList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
Type valueType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
CustomList<Object> list = new CustomList<Object>();
for (JsonElement item : json.getAsJsonArray()) {
list.add(ctx.deserialize(item, valueType));
}
return list;
}
}
Register it like this:
Gson gson = new GsonBuilder()
.registerTypeAdapter(CustomList.class, new CustomListConverter())
.create();
I need to convert a java object (called org) to json format.
The object (DTO ) is a bit complex, because it contains a list of objects of the same class and which in turn can also contain more objects of the same class ( built recursively). When I passing the object to gson.toJsonTree method it seems to fail (there isnt any error), but it seems that the method does not like complex objects). If I set to null the list of objects of the first object everything works fine. I can not modify the class, only the method that makes json.
JsonElement jsonUO = null;
jsonUO = gson.toJsonTree(org,OrgDTO.class);
jsonObject.add("ORG", jsonUO)
public class OrgDTO implements Serializable{
private String id;
......
private List sucesores;
public OrgDTO(){
this.sucesores = new ArrayList();
}
.....
}
It might be a little bit late for the questioner, however I share my answer in case someone else face similar issue:
You'll need to create a helper class that does the json serialization. It should implement the JsonDeserializer:
public class OrgDTOJsonSerializer implements JsonDeserializer<OrgDTO> {
#Override
public JsonElement serialize(OrgDTO src, Type type, JsonSerializationContext jsc) {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("id", src.getId());
/// Build the array of sucesores (whatever it means!)
JsonArray sucesoresArray = new JsonArray();
for (final OrgDTO obj: src.getSucesores()) {
JsonObject succJsonObj = serialize(obj, type, jsc);
sucesoresArray.add(succJsonObj);
}
jsonObject.add("sucesores", sucesoresArray);
return jsonObject;
}
}
Then you'll need to register it in gson before attempting to serialize any object of that type:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(OrgDTO.class, new OrgDTOJsonSerializer());
I need a mechanism for calling remote methods on server which handles type hierarchy correctly. For example GWT can do this, but my client isn't javascript! By handling type hierarchy, I mean transfering child objects even when the type is declared as a parent class! Suppose we have a class Container:
class Parent {
String name;
}
class Child extends Parent {
String family;
}
class Container {
Parent p;
}
And I have a method on server with the following signature:
void doSomethingImportant(Container c) {}
If I call this method on client, and pass an instance of Container, which has an instance of Child as property "p", I expect to get an instance of Child on server too (which would have "family" property)!
GWT handles this without any problem, is there any other technologies that can handle this?
I didn't find a RPC mechanism for this, but I managed to use JSON in order to handle this. I found Gson which is google's API for using JSON in java. It converts objects to JsonElements which can be interpretted as Strings and vice versa.
So the key feature that helped me develop this, was Gson's custom Serializer/Deserializer. I implemented a class which is Serializer and Deserializer for Object, and I send the class name for source class along the class's content:
class MySerializerAndDeserializer implements JsonSerializer<Object>, JsonDeserializer<Object>{
public JsonElement serialize(Object src, Type typeOfSrc,
JsonSerializationContext context) {
Class clazz = src.getClass();
JsonElement serialize = context.serialize(src);
JsonArray array = new JsonArray();
array.add(new JsonPrimitive(clazz.getName()));
array.add(serialize);
return array;
}
public Object deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonArray array = json.getAsJsonArray();
String asString = array.get(0).getAsString();
Object deserialize = null;
try {
deserialize = context.deserialize(array.get(1).getAsJsonObject(), Class.forName(asString));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return deserialize;
}
}
and then I registered MySerializerAndDeserializer for Parent.class:
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Parent.class, new MySerializerAndDeserializer());
And finally used gson and got the Instance I expected correctly:
String json = gson.toJson(container, Container.class);
Container containerFromJson = gson.fromJson(json, Container.class);
Using sfnrpc (http://code.google.com/p/sfnrpc) you can specify which type must be used optionally in the class arguments.
Hope this helps.
Object [] objArr = new Object[1];
TestObject to = new TestObject();
to.data = "HELLO,";
objArr[0] = to;
**Class [] classArr = new Class[1];
classArr[0] = TestObject.class;**
TestObject response = (TestObject)rpcc.invoke("#URN1","127.0.0.1:6878","echo",true,60,"", objArr,classArr);
sl.debug("The response was:"+response.data);
This is an example of the kind JSON I'm trying to consume using GSON:
{
"person": {
"name": "Philip"
"father.name": "Yancy"
}
}
I was wondering if it were possible to deserialize this JSON into the following structure:
public class Person
{
private String name;
private Father father;
}
public class Father
{
private String name;
}
So that:
p.name == "Philip"
p.father.name == "Yancy"
Currently I am using #SerializedName to obtain property names containing a period, e.g.:
public class Person
{
private String name;
#SerializedName("father.name")
private String fathersName;
}
However, that's not ideal.
From looking at the documentation it doesn't appear to be immediately possible but there may be something I have missed - I'm new to using GSON.
Unfortunately I cannot change the JSON I'm consuming and I'm reluctant to switch to another JSON parsing library.
As far as I understand you can't do it in a direct way, because Gson will understand father.name as a single field.
You need to write your own Custom Deserializer. See Gson user's guide instructions here.
I've never tried it, but it doesn't seem to be too difficult. This post could be also helpful.
Taking a look at Gson's user guide and the code in that post, you'll need something like this:
private class PersonDeserializer implements JsonDeserializer<Person> {
#Override
public Person deserialize(JsonElement json, Type type,
JsonDeserializationContext context) throws JsonParseException {
JsonObject jobject = (JsonObject) json;
Father father = new Father(jobject.get("father.name").getAsString());
return new Person(jobject.get("name").getAsString(), father);
}
}
Assuming that you have suitable constructors...
And then:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Person.class, new PersonDeserializer());
Gson gson = gsonBuilder.create();
Person person = gson.fromJson(jsonString, Person.class);
And Gson will call your deserializer in order to deserialize the JSON into a Person object.
Note: I didn't try this code, but it should be like this or something very similar.
I couldn't do this with just Gson. I need a new library 'JsonPath'. I used Jackson's ObjectMapper to convert the object to string but you can easily use Gson for this.
public static String getProperty(Object obj, String prop) {
try {
return JsonPath.read(new ObjectMapper().writeValueAsString(obj), prop).toString();
} catch (JsonProcessingException|PathNotFoundException ex) {
return "";
}
}
// 2 dependencies needed:
// https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
// https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path
// usage:
String motherName = getProperty(new Person(), "family.mother.name");
// The Jackson can be easily replaced with Gson:
new Gson().toJson(obj)