Home > Software engineering >  How to change json field names in bulk
How to change json field names in bulk

Time:05-06

I have some json in a hashmap<string, object> and i’m using ObjectMapper to map it json. I need to change the field names of pretty much all of the values. ex: change this

{ “field1”:”abc”, “field2”: “xyz”}

to this

{“f1”:”abc”, “f2”:”xyz”}

I’ve read about using Jackson and using annotation @JsonProperty, but in my case it’s just not feasible because i need to change the names of atleast 20 fields. What’s the best way to do this?

CodePudding user response:

Why can’t you change ur inout source? Such large change is unnecessary and taxing

CodePudding user response:

If you are parsing this Json with ObjectMapper, after getting intermediate DTO you can apply Mixin and export into String and then convert to required DTO.

  • Convert String to OriginalDTO with field1
  • Set Jackson mixin to object mapper
ObjectMapper mapper = new ObjectMapper();

@Getter
@Setter
public abstract class FinalMixin {
  
  @JsonProperty("f1")
  private String field1;
}

mapper.addMixInAnnotations(OriginalDTO.class, FinalMixin.class);
  • Convert DTO that you get in step 1 into String
  • Convert result String into FinalDTO
  • Related