您可以使用@JsonProperty
註釋在傑克遜中實現此目的。
public class Pojo {
@JsonProperty(value = "st")
private long stateTag;
@JsonProperty(value = "cs")
private long contentSize;
@JsonProperty(value = "ct")
private Content content;
//getters setters
}
public class Content {
@JsonProperty(value = "ty")
private String type;
@JsonProperty(value = "val")
private String value;
}
public class App {
public static void main(String... args) throws JsonProcessingException, IOException {
ObjectMapper om = new ObjectMapper();
Pojo myPojo = new Pojo(1, 10, new Content("string", "sid"));
System.out.print(om.writerWithDefaultPrettyPrinter().writeValueAsString(myPojo));
}
輸出:
{
"st" : 1,
"cs" : 10,
"ct" : {
"ty" : "string",
"val" : "sid"
}
}
解決方案2(使用自定義序列化):
該解決方案是專門針對你的POJO,這意味着每一個POJO,您將需要一個新的串行器。
public class PojoSerializer extends JsonSerializer<Pojo> {
@Override
public void serialize(Pojo pojo, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
/* your pojo */
jgen.writeStartObject();
jgen.writeNumberField("st", pojo.getStateTag());
jgen.writeNumberField("cs", pojo.getContentSize());
/* inner object */
jgen.writeStartObject();
jgen.writeStringField("ty", pojo.getContent().getType());
jgen.writeStringField("val", pojo.getContent().getValue());
jgen.writeEndObject();
jgen.writeEndObject();
}
@Override
public Class<Pojo> handledType() {
return Pojo.class;
}
}
ObjectMapper om = new ObjectMapper();
Pojo myPojo = new Pojo(1, 10, new Content("string", "sid"));
SimpleModule sm = new SimpleModule();
sm.addSerializer(new PojoSerializer());
System.out.print(om.registerModule(sm).writerWithDefaultPrettyPrinter().writeValueAsString(myPojo));
溶液3(使用命名策略): 該解決方案是一種一般的解決方案。
public class CustomNamingStrategy extends PropertyNamingStrategyBase {
@Override
public String translate(String propertyName) {
// find a naming strategy here
return propertyName;
}
}
ObjectMapper om = new ObjectMapper();
Pojo myPojo = new Pojo(1, 10, new Content("string", "sid"));
om.setPropertyNamingStrategy(new CustomNamingStrategy());
System.out.print(om.writerWithDefaultPrettyPrinter().writeValueAsString(myPojo));
我認爲這將節省帶寬是最小的,則可以通過將具有長鍵和短鍵的客戶端/服務器端之間的映射卸載從網絡存儲。 –
在客戶端用戶將不得不解釋您所需的json?爲什麼不使用Apache deflate選項http://stackoverflow.com/questions/19254859/does-apache-2-gzip-json-output-by-default – gurvinder372
這是一個例子http://thegeekyland.blogspot.com/2015/ 11/serializing-and-deserializing-json-from.html – Arlind