English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Некоторые вопросы о注解 @JSONField в fastjson (подробное объяснение)

@JSONField

查看源码可以看出它可以作用于字段和方法上。

引用网上的说法,

一、作用Field

@JSONField动作在Field时,其name不仅定义了输入key的名称,同时也定义了输出的名称。

But in my use, I found that it is not as described above.

For example

@JSONField(name="project_id")
private Long ProjectID

I found that when bean is converted to json, it is not in the form of "project_id":xxx, and when json is converted to bean, the content of "project_id":xx will not be set to ProjectID inside.

The version of fastjson is 1.1.15

Part two: used on setter and getter methods This method is actually in line with expectations during use.

/**bean 转json 时会把bean中的ProjectID转换为project_id */
  @JSONField(name="project_id")
  public Long getProjectID() {
    return ProjectID;
  }
/**json 转bean 时会把json中的project_id值赋值给projectID*/
  @JSONField(name="project_id")
  public void setProjectID(Long projectID) {
    ProjectID = projectID;
  }

Part three: other usages of @JSONField, see the source code of @JSONField annotation, in addition to name, format, serialize, deserialize, serialzeFeatures, parseFeatures are available,

•format,It seems to be useful for formatting date formats in fields of Date type.

•serializeand deserialize are boolean types, the usage is

@JSONField(serialize=false) 
private Long ProjectID

It does not include this field when serializing. Deserialization is the opposite. However, there is something to note, I have seen other places say that when the field is final, the annotation placed on the field does not take effect, and it should be placed on the get

or on the set method.

•serialzeFeaturesI use this property, by default, fastjson does not serialize this field when the field value is null, for example, I have such a requirement

{"fieldName":"project_id","operator":"is not","value":null}

An object is serialized in this way, my code is as follows

CriteriaVO criteriaVO = new CriteriaVO();
    criteriaVO.setFieldName("project_id");
    criteriaVO.setOperator("is not");
    criteriaVO.setValue(null);

По умолчанию он будет сериализован следующим образом

{"fieldName":"project_id","operator":"is not"}

Конечно, fastjson позволяет вам контролировать правила сериализации

Это использует SerializerFeature, это энум, который содержит несколько значений, если у вас есть интерес, вы можете узнать их подробнее

Я использовал только один из них

@JSONField(serialzeFeatures=SerializerFeature.WriteMapNullValue)
private String value;

Таким образом, когда значение value равно null, он все равно будет сериализован. Вот такой вид, это именно результат, который я хотел получить

{"fieldName":"project_id","operator":"is not","value":null} 

Я снова встретил другую проблему, когда тип поля равен int, например

private int start;
private int limit;

Если я не установлю значение, он будет сериализован следующим образом

"limit":0,"start":0

По умолчанию они все установлены в 0, а моя цель - чтобы они не появлялись, если не устанавливать значения.

Я просто изменил их тип на Integer. Должно быть и других способов решения проблемы через настройку поведения сериализации, но на данный момент не будем это исследовать.

Вот и все, что я хочу поделиться с вами о некоторых вопросах, связанных с аннотацией @JSONField в fastjson (подробно). Надеюсь, это поможет вам, и希望大家多多 поддерживать呐喊 руководства.

Основной курс
Ты может понравится