0

I am trying to get a JSON Object from an object but it fails with below exception

at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)

Searched on internet and solutions provided are @JSONIgnore , @JSONBackReference but my project is so huge that I can't afford to change any existing entity.

Is there some other way we can get away with the cyclic dependency and get a proper json string from the object?

monika
  • 28
  • 1
  • 1
  • 2
  • http://stackoverflow.com/questions/13764280/how-do-i-exclude-fields-with-jackson-not-using-annotations – Amit Parashar Jul 05 '16 at 12:39
  • Thanks Amit, but here also we are either defining specific fields or adding annotations to POJO classes, which I don't want to do. – monika Jul 06 '16 at 10:18

1 Answers1

0

I could solve the problem by using Gson ExclusionStrategy as below

class MyExclusionStrategy implements ExclusionStrategy {
Set<String> encounteredClasses = new HashSet<String>();

public boolean shouldSkipField(FieldAttributes fa) {
    return false;
}

@Override
public boolean shouldSkipClass(Class<?> type) {
    System.out.println(encounteredClasses);
    if (encounteredClasses.contains(type.getSimpleName().toString())) {
        return true;
    } if (type.isAnnotationPresent(Entity.class)) {
        encounteredClasses.add(type.getSimpleName().toString());
    }
    return false;
}}

Here it would keep adding the already encountered classes to a set and if encounters the same again, it would skip.

monika
  • 28
  • 1
  • 1
  • 2