1

I have this object structure which I'm trying to annotate with Jackson to marshal/unmarshal to a JSON file.

public class A {
    List<B> bList;
}

public class B {
    String attr;
    Map<String, C> map;
}

public class C {
    @JsonIgnore
    String name;
    String value;
}

A has a list of B's and B has a map of C's where the key of the map is the name attribute of C. I want the JSON to look like this if possible:

{
    "bList" : [
               {
                   "attr":"itsValue"
                   "KEY_IN_MAP":"VALUE_IN_C",
                   "KEY_2_IN_MAP":"VALUE_2_IN_C"
               }
               ]
}

Where KEY_IN_MAP is the name of C as the key in B's map and VALUE_IN_C is the value of the value object in the map. I've tried annotating a put method for the map:

@JsonAnySetter
private void put(String name, C value) {
    map.put(name, c);
}

But marshaling this gives me:

{
    "bList" : [
               {
                   "attr":"itsValue"
                   "KEY_IN_MAP": {
                       "value":"VALUE_IN_C",
                   },
                   "KEY_2_IN_MAP": {
                       "value":"VALUE_2_IN_C"
                   }
               }
               ]
}

Is there any way to get the above mapping with Jackson or any other JSON serializing library? My goal is to get rid of the redundancy of writing "value" every time and compress the file as much as possible.

The map in B could be turned into a list of C but I still need the mapping to be

{"name" : "value"} for each object C
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724

1 Answers1

1

Here are few suggestions that I have:

  1. Make your Map<String,C> to be a Map<String,String>.
  2. You can also make your Map<String,C> to be List<C>.

Please have a look at the other thread which discusses the same.

Community
  • 1
  • 1
Srinivas
  • 1,780
  • 1
  • 14
  • 27