Search code examples
javajsonspring-bootfastjson

@JSONField it did not work in spring boot


I use @JSONField annotation for pointX and pointY, I want to change pointX to point_x! I want to pointX show like point_x! But it did not work! It always is pointX and pointY! but other field is ok!

My java bean like this!

@Data
public class PointListOutput {
  
    @JSONField(name = "latest_area_point_list")
    private List<Point> latestAreaPointList;

    @Data
    public static class Point {
        @JSONField(name = "point_x")
        private Float pointX;
        @JSONField(name = "point_y")
        private Float pointY;
    }
}

my config

@Override
protected void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);

    // create FastJson converter
    final FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();

    final List<MediaType> supportedMediaTypes = new ArrayList<>();
    supportedMediaTypes.add(MediaType.APPLICATION_JSON);
    supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
    converter.setSupportedMediaTypes(supportedMediaTypes);

    // create configuration class
    final FastJsonConfig config = new FastJsonConfig();
    // update filter of response
    config.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
    converter.setFastJsonConfig(config);

    converters.add(new ByteArrayHttpMessageConverter());
    converters.add(converter);
}

Here is my http response, as you can see the pointX is pointX! not point_x!

{
    "code": 1,
    "message": "Success",
    "data": [
        {
            "latest_area_point_list": [
                {
                    "pointX": 1.1,
                    "pointY": 1.1
                },
                {
                    "pointX": null,
                    "pointY": 1.1
                }
            ]
        }
    ]
}

Solution

  • I resolved this, it cause by org.springframework.beans.BeanUtils.copyProperties
    I used org.springframework.beans.BeanUtils.copyProperties change DAO java bean to View java bean.
    My Dao java bean

    @Data
    @DynamoDBTable(tableName = "xxxx")
    public class PointPojo {
        @DynamoDBAttribute(attributeName = "latest_area_point_list")
        private List<Point> latestAreaPointList;
    
        @Data
        @DynamoDBDocument
        public static class Point {
            @DynamoDBAttribute(attributeName = "point_x")
            private Float pointX;
            @DynamoDBAttribute(attributeName = "point_y")
            private Float pointY;
        }
    }
    

    And PointPojo did no hava @JSONField(name = "point_x")
    after copyProperties the Point was not PointListOutput$Point, it was PointPojo@Point, and it did not hava @JSONField(name = "point_x")
    So this is the root cause!

    I use orika replace org.springframework.beans.BeanUtils.copyProperties, it was perfect!