Is there a JSON library that can serialize Proxy objects? - java

Using ActiveObjects as my ORM and Gson as my JSON processor.
Ran into a problem going toJson from
persisted objects. The problem is that my persisted class is actually
an Interface and AO is proxying that object under the hood. Here's
some sample code:
Venue venue = manager.get(Venue.class, id);
gson.toJson(venue);
Comes up with this exception:
java.lang.UnsupportedOperationException: Expecting parameterized type,
got interface java.lang.reflect.InvocationHandler.
Are you missing the use of TypeToken idiom?
See http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and...
Because venue.getClass().getName() gives:
$Proxy228
I've tried a few solutions in various combinations:
gsonBuilder.registerTypeAdapter(Venue.class, newVenueSerializer());
Type listType = new TypeToken<Venue>() {}.getType();
Nothing has worked so far and I'm using a wonky field-by-field workaround. Any suggestions? I'm not married to Gson, so if there's an alternative library that can do this I'd be happy to use it.

Flex JSON should work - it will use the bean property introspector to pull the object, and I assume the proxy class implements those properly.

Also check out the Jackson.

Related

How to convert JSON in QueryParams into Object in Java Spring?

I have this query
http://localhost:8555/list/csv?search={}
Where search is a json object (omitted other params as they are irrelevant here).
How can i convert this into a nested object?
public record CsvParams<T>(
T search,
/* Other query params */ ) {}
Right now im getting error that string cannot be cast into object.
class java.lang.String cannot be cast to class classname
Is there anyway to do this? Old solution uses ObjectMapper to convert string into corresbonding object. I was hoping that maybe there is a way to do it more simpli and remove this boilerplate.
Any single value of a query param can't be automatically converted to a non-primitive type. You can convert multiple params to a class, but not one that happens to be a JSON AFAIK. But you can create a converter custom deserialiser and then use it in different controllers, but in the end you'd still use an ObjectMapper.
More info on how to do the latter here: https://www.baeldung.com/spring-mvc-send-json-parameters
If you have to work with query params than I don't think you can have it converted automatically by Spring boot. But if you work with POST or PUT methods and can pass your params as request params in request body your JSON params can be automatically converted to class instances by Spring boot and no effort required from you. However, if you have to work with query param (say you have to use method GET so you have no request body) than you can use Json-Jackson library or Gson library to parse your Json into class instance. If you use Jackson you will need to use class ObjectMapper. For Jackson lib info see this site, for ObjectMapper class see Javadoc here. However, I wrote my own JsonUtils that is very good for simple usecases like yours. It allows to to parse simple JSON into a class with a single method. It is very simple and strait forward. It is a thin wrapper over Jackson library. See the Javadoc for method readObjectFromJsonString. Class JsonUtils is part of Open Source MgntUtils library. You can get it as Maven artifact on Maven Central and as a jar (with source code and Javadoc) on Github

JsonJackson not adding #class

I am using kotlin with redisson and jsonjackson as the serializer. Previously when I used jackson in java, it would automatically add a '#class' tag to the json so when I came to deserialize it, it would work fine and redisson would know what class to use. Now it no longer does this and when I try to get something out of an RMap<UUID, UserProfile> (UserProfile is an interface", it gives an error which says "jacksonjson missing type id property '#class'" which is obvisouly due to the json missing the '#class' tag.
Anyone know how I can fix this and have jackson automatically add the #class tag like it previously did? Thank you
Fixed this by adding #JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) to the implementation class

Serialize vertx JsonObject using Jackson

I'm using vertx and Jackson in my development. In one of my classes, I got a field of type JsonObject, something like this:
class User
private String name;
private JsonObject details;
This details field can contain other JsonObjects or JsonArrays, e.g.:
{"details": [{"street": "Broadway"}, {"building": 20}]}
I don't have a dedicated class of this structure, as far as there's no fixed structure and it can vary.
details object is being created in the way like this:
JsonObject details = new JsonObject().put("name", "value").put("another", "another")
This aproach allows me to store details of any structure inside my code. As far as I don't need to manipulate this data on my backend, I don't want to create a special structure for it.
Everything works fine until I'm trying to serialize this JsonObject using Jackson. Unfortunately, instead of beatiful JSON string, Jackson gives me map object serialized with all map's additional fields.
How can I serialize JsonObject of vertx using Jackson?
Looking at JsonObject's javadoc , I saw a getMap() method. I know Jackson is capable of serializing Maps with ease.
Finally, it turned out that vertx already has it's own implementation of Serializer.
It's enough just to use theirs class to perform serialization (which will use Jackson undercover).
JsonObject user = new JsonObject(Json.encode(new User());
And it works fine.
I would suggest creating using https://static.javadoc.io/com.fasterxml.jackson.core/jackson-databind/2.7.3/com/fasterxml/jackson/databind/ObjectMapper.html#convertValue(java.lang.Object,%20java.lang.Class) like this:
new JsonObject((Map)Json.mapper.convertValue(new User(), Map.class));
Converting to and from String takes time.

Jackson Deserialization of List with Default Typing

Good Day,
Hi All,
I'm trying to configure the Jackson Object Mapper to de-serialize any json String to my domain specific objects.
I've configured the Object Mapper as below
ObjectMapper mapper = new ObjectMapper();
mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.enableDefaultTypingAsProperty(DefaultTyping.NON_FINAL, "remoteClass");
In my domain, any json string should contain a remoteClass property which denotes the actual JAVA POJO (canonical name) that it corresponds to. The above configuration helps resolve abstract types
However with the above, now java.util.Lists are not getting properly deserialized, since they are abstract types.
I get the following error
Unexpected token (START_OBJECT), expected VALUE_STRING: need JSON String that contains type id (for subtype of java.util.List)
Object Mapper in this case is not resorting to the default collectionFallBacks
I tried other configuration to overcome the issue such as
SimpleModule module = new SimpleModule("test", Version.unknownVersion());
module.addAbstractTypeMapping(List.class, ArrayList.class);
mapper.registerModule(module);
However these lead to other problems.
Can someone please help me with the same. I've spent days on this now. This seems like a limitation in Jackson. Correct me if I'm wrong
I faced this problem recently. Try this, in your POJO, instead of defining property as
List<SimpleModule>
define it as
List<Object>.

How to add class name when serialize to json by net.sf.json

I am planning to provide a interface to iOS Apps, the developer asked to add an additional field call class contains the name of the pojo I used on server so he can convert to his class on client easily. The problem is I have to do this when the json lib is processing the values.I think the registerJsonValueProcessor can do the trick. I got then class name by obj.getClass().getName() but I still have no idea how to attach it to json-lib.
If you are using jackson for serialization/deserialization of json than please apply the annotation JsonTypeInfo on your class. It could help you
#JsonTypeInfo(use=Id.CLASS, include=As.PROPERTY, property="class")

Categories

Resources