JSON to java object returing LinkedHashMap - java

I have below json string :-
{"name":"Test","sortlist":[],"filterlist":[{"fieldname":"regions_id","operator":"equals","value":{"id":1,"code":"HIGH","description":"HIGH Region","comment":"High Region","active":true}}]}
and Java class as below :-
#JsonSerialize
#JsonDeserialize
public class ItemFilter implements Serializable {
private String name;
private List<FieldFilter> filterlist = new ArrayList<FieldFilter>();
}
public class FieldFilter implements Serializable {
private static final long serialVersionUID = 1L;
private String fieldname;
private String operator;
private Object value;
}
and my convert method as below :-
public static ItemFilter convertItemFilter(String item) {
ObjectMapper mapper = new ObjectMapper();
try {
ItemFilter itemFilter = mapper.readValue(item, new TypeReference<ItemFilter>(){});
return itemFilter;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
ItemFilter domain is getting converted correctly but in private Object value; field i am getting LinkedHashMap i want to get an simple object and later i will type cast it.
Can someone please guide me how to escape LinkedHashMap and get an simple Java Object in variable?
i cant use hard coding Object type because its a generic pojo which can have any object type. hard coding will make this pojo very bigger and frontend also need to change for it. So that why i have used Object as data type.

The following class structure should return the JSON to "YourObject"
public class YourObject{
private String name;
private List<String> sortList;
private List<Filter> filterList;
public static class Filter{
private String fieldname;
private String operator;
private Value value;
}
public static class Value{
private Integer id;
private String code;
private String description;
private String comment;
private Boolean active;
}
}
Then use the following to read it into the object:
YourObject itemFilter = mapper.readValue(item, YourObject.class);

Related

Yaml deserilization to POJO using Jackson

How to deserialize Yaml to POJO when a key is dynamic? I have a Yaml file with this structure:
paths
/user:
get:
summary: Example summary
description: Some description
/account
post:
summary: Another summary
description: Another description
And I need to deserialize it to a Java Object:
public class PathsWrapper {
private List<Path> paths;
}
public class Path {
private String url;
private List<Method> methods;
}
public class Method {
private String method;
private String summary;
private String description;
}
You can use a map like so:
public class PathsWrapper {
private List<Path> paths;
}
public class Path {
private Map<String,List<Method>> url;
}
public class Method {
private Map<String, MethodDescription> method;
}
public class MethodDescription {
private String summary;
private String description;
}

Representing request array in Java

I have the following request
{
"attachments":[
{
"fields":[
{
"value":"Testing value"
}
]
}
],
"channel":"testing",
"value":"Testing value"
}
and want to make it as a request in Java, but I am struggling how to represent it and use it. So far I've done this
public class RequestTest {
ArrayList<ArrayList<String>> attachments = new ArrayList<ArrayList<String>>();
ArrayList<String> fields = new ArrayList<String>();
private String channel;
private String value;
}
But I am not sure how to put the value and how to call it after that.
You have to create an object structure like:
public class RequestTest {
ArrayList<Attachment> attachments = new ArrayList<>();
private String channel;
private String value;
}
public class Attachement {
ArrayList<Field> fields = new ArrayList<>();
}
public class Field {
String value;
}
Then you can use jackson or gson to create the json string you expect.
If you want to present the request in Java class, then you should create a class named "Field" and class named "Attachment".
public class Field{
private String value;
}
public class Attachment{
private List<Field> fields;
}
public class RequestTest{
private List<Attachment> attachments;
private String channel;
private String value;
}
If you want to present it with JsonObject, you can refer to JsonObject

I want to remove few fields from JSON result field T result. I am not able to to delete specific fields from T result

As per code given i want to remove few fields from in ResultJSON.
In field I am going pass list of ResultBean.
I am setting fields in result field like resultJson.setResult(ResultBeanList)
Note: ResultBean is not a JSON object. It simple Java bean.
Hope You understand my issue.
public class ResultJson<T> {
private Integer success;
private T result;
private String message;
private String errorCode;
}
public class ResultBean implements Serializable {
private static final long serialVersionUID = 1L;
private String customerName;
private String customerCode;
private String customerAlias;
private String pOR;
private String pOD;
}
We can skip/remove fields in JSON but question how can we delete fields from inside of JSON fields.

How to deserialize a generic object at runtime with Jackson

Say I have the following java classes (getters & setters omitted for brevity).
public class AllMyEvents {
private List<SomeEvent<?>> eventList;
}
public class SomeEvent<T> {
private long time;
#JsonProperty("event_type")
private String eventType;
#JsonProperty("event_data")
private T eventData;
}
public class BigEvent {
private List<SomeEvent<LittleEvent>> subEvents;
}
public class LittleEvent {
private long data;
}
When I call:
ObjectMapper om = new ObjectMapper();
AllMyEvents events = om.readValue(IOUtils.toString(jsonData, "UTF-8"),AllMyEvents.class);
The field eventData is of type LinkedHashMap. What I want is for this fields type to be specified by the eventType string. If the string is 'big' I want eventData to have type BigEvent or LittleEvent if the string is 'little'.
Is it possible to do this with Jackson annotations, or will I need to write a custom serializer/deserializer, or some other method? I'm using Jackson 1.9 if that is relevant.
Json Sub types is your answer.
#JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="#class")
#JsonSubTypes({
#JsonSubTypes.Type(value=BigEvent.class, name="big"),
#JsonSubTypes.Type(value=LittleEvent.class, name="little")
})
public class SomeEvent<T> {
private long time;
#JsonProperty("event_type")
private String eventType;
...
Also see: http://wiki.fasterxml.com/JacksonPolymorphicDeserialization

How to deserialize JSON Array contained an abstract class without modifying a parent class?

I'm trying to deserialize JSON Array, which is persisted into my MongoDB, to a Java object by using Jackson. I found many tutorials mentioned to handle this polymorphism by adding:
#JsonTypeInfo(use=Id.CLASS,property="_class")
to a Super-class. However, in my case, I can't be able to modify the Super-class. So, are there some solutions to solve it without modifying the Super-class? Here is my code:
public class User {
#JsonProperty("_id")
private String id;
private List<Identity> identities; // <-- My List contains objects of an abstract class; Identity
public User(){
identities = new ArrayList<Identity>();
}
public static Iterable<User> findAllUsers(){
return users().find().as(User.class); // Always give me the errors
}
/*More code*/
}
It always give me the error - Can not construct instance of securesocial.core.Identity, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information.
You can use #JsonDeserilize annotation to bind a concrete implementation class to an abstract class. If you cannot modify your abstract class you can use the Jackson Mix-in annotations to tell Jackson how to find the implementation class.
Here is an example:
public class JacksonAbstract {
public static class User {
private final String id;
private final List<Identity> identities;
#JsonCreator
public User(#JsonProperty("_id") String id, #JsonProperty("identities") List<Identity> identities) {
this.id = id;
this.identities = identities;
}
#JsonProperty("_id")
public String getId() {
return id;
}
public List<Identity> getIdentities() {
return identities;
}
}
public static abstract class Identity {
public abstract String getField();
}
#JsonDeserialize(as = IdentityImpl.class)
public static abstract class IdentityMixIn {
}
public static class IdentityImpl extends Identity {
private final String field;
public IdentityImpl(#JsonProperty("field") String field) {
this.field = field;
}
#Override
public String getField() {
return field;
}
}
public static void main(String[] args) throws IOException {
User u = new User("myId", Collections.<Identity>singletonList(new IdentityImpl("myField")));
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Identity.class, IdentityMixIn.class);
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(u);
System.out.println(json);
System.out.println(mapper.readValue(json, User.class));
}
}

Categories