I am attempting to deserialize JSON which can be either a GroupRule or AttributeRule:
AbstractRule
GroupRule
AttributeRule
I want my models/entities/POJOs to be generic as I also use the same classes in other projects with Snakeyaml or other serialization providers.
Having said that, I stumbled across this: https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization
which in the article, it indicates I could do:
{ // Using fully-qualified path
"#class" : "com.fasterxml.beans.EmployeeImpl", ...
}
However, when I do that, I am getting:
Cannot construct instance of `com.walterjwhite.email.organization.api.configuration.rule.AbstractRule` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (FileInputStream); line: 4, column: 10] (through reference chain: com.walterjwhite.email.organization.api.configuration.rule.EmailMatcherRule["rule"])
com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
My configuration is this:
{
"name": "default",
"ordering": "1",
"rule": {
"#class": "com.walterjwhite.email.organization.api.configuration.rule.GroupRule",
"criteriaType": "Should",
"rules": [
{"#class": "com.walterjwhite.email.organization.api.configuration.rule.AttributeRule",
"emailMessageField": "Subject",
"values": ["default"]
}
]
},
"matchType": "ContainsIgnoreCase",
"actionClassNames": [
"com.walterjwhite.email.organization.plugins.count.CountAction",
"com.walterjwhite.email.organization.plugins.index.IndexAction",
"com.walterjwhite.email.organization.plugins.reply.MoveAction"
]
}
On the Java side of things, I am doing this generally:
mapper.readValue(inputStream, entityType);
Now, the entityType in this case is EmailMatcherRule which inside it has a rule field which can either be attribute or group. Inputstream is just the fileInputStream I am passing in ...
I am using Jackson 2.10.1. I also converted the above JSON from YAML which was working fine via Snakeyaml. Note that it automatically embeds the classes into the YAML, so this was a non-issue with it.
Is my JSON correct - according to the documentation, I should be able to add the #class attribute to specify the class I want to use, right?
I tried below and it worked without any configuration. Not sure if thats what you want to achieve:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String groupRuleStr = "{\"parentId\":\"parent\",\"groupId\":\"group\"}";
String attributeRuleStr = "{\"parentId\":\"parent\",\"attributeId\":\"attribute\"}";
GroupRule groupRule = mapper.readValue(groupRuleStr, GroupRule.class);
AttributeRule attributeRule = mapper.readValue(attributeRuleStr, AttributeRule.class);
System.out.println(groupRule.groupId);
System.out.println(attributeRule.attributeId);
}
static abstract class AbstractRule {
public String parentId = "parent";
}
static class GroupRule extends AbstractRule {
public String groupId = "group";
}
static class AttributeRule extends AbstractRule {
public String attributeId = "attribute";
}
I had to do this:
objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator());
Now, my JSON looks like this (NOTE: this is a different test entity, but you get the idea):
{
"name": "default",
"ordering": "1",
"rule": [
"com.walterjwhite.email.organization.api.configuration.rule.GroupRule",
{
"criteriaType": "Should",
"rules": ["java.util.HashSet",[[
"com.walterjwhite.email.organization.api.configuration.rule.AttributeRule",
{
"emailMessageField": ["com.walterjwhite.email.organization.api.configuration.rule.EmailMessageField", "Subject"],
"values": ["java.util.HashSet", [
"default"
]],
"matchType": ["com.walterjwhite.email.organization.api.configuration.rule.MatchType","ContainsIgnoreCase"]
}]]
]
}
],
"actionClassNames": ["java.util.ArrayList",[
"com.walterjwhite.email.organization.plugins.count.CountAction",
"com.walterjwhite.email.organization.plugins.index.IndexAction",
"com.walterjwhite.email.organization.plugins.reply.MoveAction"
]
]
}
So, the reference documentation I saw with #class seems inaccurate. I am not really happy about adding all this extra information especially when some of it isn't needed - java.util.ArrayList.
Related
I am working on parsing a GeoJSON file into Java POJO classes.
I have found the GeoJSON Jackson library which seems to be exactly the same as I need.
https://github.com/opendatalab-de/geojson-jackson
I have a JSON like the following:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"lfdNr": 1,
"betriebsNummer": 33,
"nummer": 4,
"bezeichnung": "TERST",
"kng": 61062323,
"nArtCode": "A",
"nArtB": "ACKERLAND",
"flaeche": 4.0748
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
15.8867118536754,
48.4004384452486
],
[
15.884483831836,
48.3981983444393
],
[
15.8847389374202,
48.3991957290405
],
[
15.8853143451339,
48.3991585954555
],
[
15.8851662097189,
48.398462039698
],
....
]
]
}
}
]
}
I wish to use it as a FeatureCollection java object:
objectMapper.readValue(json, FeatureCollection.class);
I get the following:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct
instance of `org.geojson.GeoJsonObject`
(no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types,
have custom deserializer, or contain additional type information
at [Source: (String)"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"lfdNr":1,"betriebsNummer":10086722,"nummer":4,"bezeichnung":"TERST","fskennung":61062323,"nutzungsArtCode":"A","nutzungsArtBezeichnung":"ACKERLAND","flaeche":4.0748},"geometry":{"type":"Polygon","coordinates":[[[15.8867118536754,48.4004384452486],[15.8829132747878,48.4002081767679],["[truncated 2362 chars]; line: 1, column: 251]
(through reference chain: org.geojson.FeatureCollection["features"]->java.util.ArrayList[0]->org.geojson.Feature["geometry"])
I assume it is because the class Geometry a generic type is:
public abstract class Geometry<T> extends GeoJsonObject
I only operate with Polygons and Points.
Any ides how can I get it working?
Thanks a lot!
You can read this JSON content by
GeoJsonObject object = objectMapper.readValue(json, GeoJsonObject.class);
if (object instanceof FeatureCollection) {
FeatureCollection featureCollection = (FeatureCollection) object;
...
}
Jackson will automatically recognize your JSON example as a FeatureCollection object,
because of the annotations on the GeoJsonObject class:
#JsonTypeInfo(property = "type", use = Id.NAME)
#JsonSubTypes({ #Type(Feature.class), ..., #Type(FeatureCollection.class), ... })
...
public abstract class GeoJsonObject implements Serializable {
...
}
I need to create response POJOs class for a couple of APIs i have to call in my microservice . The response has a base structure given below.
{
"requestId": "abcd-1234-3456",
"sourceSystem": "HOME",
"response": {
"statusCode": "200",
"statusMessage": "Successfully Received",
"statusType": "SUCCESS",
"details": [
{
"message" : "hi"
}
]
}
}
Here the object inside the "details" property array can vary and can have different class definitions. Can someone help whether how should i declare my POJOs so that there is a common class for the common fields and a different set of classes for object inside details property . I tried few ways using java generics and #JsonSubType but that is giving some error Unrecognized field "details" during deserialisation.
Why don't you try and define it as object instead :-
class Response{
private String requestId;
private String statusMessage;
private String statusType;
private List<Object> details;
}
I have got two main model classes: Customer and Product
public class Customer {
String name;
String surname;
int age;
BigDecimal cash;
}
public class Product {
String name;
Category category;
BigDecimal price;
}
I want to build json file with Map<Customer, List<Product>>
When I write to json file data with my method which works correct - I am sure about this - the json file shows this syntax
{
"Customer{name\u003d\u0027Custo1\u0027, surname\u003d\u0027Surname\u0027, age\u003d18, cash\u003d1200}": [
{
"name": "prod1",
"category": "CLOTHES",
"price": 12000
},
{
"name": "prod2",
"category": "ELECTRONIC",
"price": 15000
}
]
}
Then when i want to read this file, the error Exception in thread "main" java.util.NoSuchElementException: No value present occurs so I think that the Customer syntax from json file is not recognized.
So I tried to write data to json file on my own with this syntax below, but it does not work
[
{
"name": "Abc",
"surname": "Def",
"age": 14,
"cash": "2000"
}
:
[
{
"name": "prod1",
"category": "CLOTHES",
"price": 12000
},
{
"name": "prod2",
"category": "ELECTRONIC",
"price": 15000
}
]
]
json converter method:
public void toJson(final T item) {
try (FileWriter fileWriter = new FileWriter(jsonFilename)) {
fileWriter.write(gson.toJson(item));
} catch (Exception e) {
throw new ValidatorException(e.getMessage());
}
}
#Tom is right on the issues you've faced with. I'll explain why and suggest one more solution.
Your first JSON is technically a valid JSON but it cannot be deserialized, because the map keys are results of the Customer.toString() method Gson uses by default. This is why it looks weird, acts like a debug string, and can't be deserialized back: there it is almost always no way to restore an object from the toString() result (toString is designed mostly for debugging/logging purposes providing basic information regarding the state of a particular object that does not need to expose its all internals at all).
Your second JSON is invalid JSON. Period.
Tom's suggestion of making the list of products a part of the customer class is totally fine. Having it implemented like that lets you to serialize everything as a list like this:
[
{
"name": "john",
"products": [
{"name": "prod1"},
{"name": "prod2"}
]
}
]
Hint: separating domain objects (Customer and Product) and representation objects for data transfer (CustomerDto and ProductDto) is usually a fine idea too since it allows to create representation for any concrete representation implementation (one for various JSON implementation libraries, two for other-format-oriented tools, third for persistence, four for UI views, etc), so it might be implemented like converting Map<Customer, List<Product>> to List<CustomerDto> and back (possibly by using mapper-generators like MapStruct).
If for whatever reason it is not possible to reorganize your domain classes or create Gson-friendly DTO-mappings, or you're fine to keep it as simple as possible and you're fine with having not that trivial JSON structure (as long as you understand implications of the format in this solution: evolution, distribution, etc), then you can enable special Gson mode to support this kind of maps. It generates valid JSONs that can be serialized and deserialized back, but the way it is implemented looks a bit of anti-pattern to me because of losing semantics due to using arrays as the data container.
#AllArgsConstructor
#EqualsAndHashCode
#ToString
final class Customer {
final String name;
}
#AllArgsConstructor
#EqualsAndHashCode
#ToString
final class Product {
final String name;
}
public final class MapTest {
private static final Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization()
.create();
private static final TypeToken<Map<Customer, List<Product>>> customerToProducts = new TypeToken<Map<Customer, List<Product>>>() {};
#Test
public void test() {
final Map<Customer, List<Product>> ordersBefore = ImmutableMap.of(
new Customer("john"), ImmutableList.of(new Product("prod1"), new Product("prod2"))
);
final String json = gson.toJson(ordersBefore, customerToProducts.getType());
Assertions.assertEquals("[[{\"name\":\"john\"},[{\"name\":\"prod1\"},{\"name\":\"prod2\"}]]]", json);
final Map<Customer, List<Product>> ordersAfter = gson.fromJson(json, customerToProducts.getType());
Assertions.assertEquals(ordersBefore, ordersAfter);
}
}
Note that it generates JSON like this (index 0 means the key, index 1 means the value):
[
[
{"name": "john"},
[
{"name": "prod1"},
{"name": "prod2"}
]
]
]
I have to deserialise below Json
{
"Student": [
{
"Number": "12345678",
"Name": "abc"
"Country": "IN",
"AreaOfInterest": [
{
“FootBall”: “Yes”,
“Cricket”: “No”
}
]
}
],
"hasMore": false,
"links": [
{
"rel": "self",
"kind": "collection"
}
]
}
into below POJO
class {
private String number;
private String name;
private String footBall;
}
I have written Gson custom deserialiser to lift up AreaOfInterest as below
public List<? extends Student> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
var jsonObject = json.getAsJsonObject();
Stream<JsonElement> student = StreamSupport.stream(jsonObject.getAsJsonArray("Student").spliterator(), true);
Stream<JsonElement> areaOfInterest = StreamSupport.stream(jsonObject.getAsJsonArray("Student").get(0).getAsJsonObject().get("AreaOfInterest").getAsJsonArray().spliterator(), true);
Stream.concat(student,areaOfInterest)
.map(it -> context.deserialize(it, Student.class))
.map(Student.class::cast)
.collect(List.collector())
}
But deserialiser returning two objects of Student instead of one, one is all fields are null except footBall other is actual student except footBall as null, any help how to get single object with all the fields will be of great help, thanks in advance.
This won't be your exact answer, but it might be simpler to use gson to obtain a map and construct your pojo from that map. Alternatively, if you don't like the map, create a pojo that looks like your JSON and map that pojo to the pojo you want.
Background/Reasoning: GSON is the mapper of your choice right now, but might be changed to something else, eg. Jackson, and all of your custom, framework specific mappers will need to be converted/changed if that happens. Using gson to create an object, that looks like the source, and map that to your custom POJO in your controller will make your codes intention clear and your code more resilient to framework changes.
I have tried add the JSON response into the Realm database. I handled the response through GSON and then tried to convert to realm. I have already extended RealmObject for my response model class. I am also using RealmString class for handling List by using RealmList. But when I tried to GSON to Realm object I get errors. I am looking for an example of this kind if anyone has one. All support are appreciated. Below is my JSON response.
{
"transactionType": 12,
"location": {
"type": "Point",
"coordinates": [
77.7,
12.9
]
},
"rooms": {
"bedrooms": {
"total": 2,
"metadata": [
{
"name": "bedroom 2",
"images": [
"Eshant",
"Abhijeet"
]
}
]
}
}
}
I answered a very similar question here https://stackoverflow.com/a/39993141/1666063
Here is short walkthrough how to to JSON -> GSON -> Realm:
Use http://www.jsonschema2pojo.org/ to generate a POJO with getters and setters for GSON
for the classes and subclasses you want to store in Realm add extends RealmObject to them
for all your classes that extends RealmObject make sure to put #PrimaryKey on of the fields (like an ID)
replace any usage of List<Foo> with RealmList<Foo>
Foo MUST extends RealmObject as well (even if it is a String)
Add a TypeAdapter to GSON that can handle RealmList(here is one I wrote that takes a generic T)