使用 jackson 将 java 对象转换为 json 字符串时复制 json 属性
2022-09-03 09:17:42
我有Pojo对象,带有getAsJson函数来返回此对象的Json字符串。我使用JsonProperty在此对象中定义json属性。使用 ObjectMapper 的 writeValueAsString 为此对象编写 json 字符串。
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
@JsonIgnoreProperties(ignoreUnknown=true)
public class LogLikeArticleDetail extends BaseObject {
private static final long serialVersionUID = -2018373118257019033L;
@JsonProperty("LikeArticleGUId")
private String likeArticleGUId;
@JsonProperty("UserId")
private String userID;
@JsonProperty("UserName")
private String userName;
@JsonProperty("IP")
private String ip;
@JsonProperty("OS")
private String os;
@JsonProperty("UserAgent")
private String userAgent;
@JsonProperty("WebsiteCode")
private String websiteCode;
@JsonProperty("ArticleId")
private String articleID;
@JsonProperty("ATitle")
private String aTitle;
@JsonProperty("CateAlias")
private String cateAlias;
@JsonProperty("LikeStatus")
private String likeStatus;
@JsonProperty("TimeStamp")
private Date timeStamp;
//get, set....
//....
@JsonIgnore
public String getAsJSON() throws JsonGenerationException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(this) ;
}
}
现在,我得到结果
public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
Calendar calendar = Calendar.getInstance();
LogLikeArticleDetail logLikeArticle = new LogLikeArticleDetail("1","2","3","4","5","6","7","8","what thing \"nothing\" show","10","11",calendar.getTime());
System.out.println(logLikeArticle.getAsJSON());
}
但结果的重复属性:
{"LikeArticleGUId":"1","UserId":"2","UserName":"3","IP":"4","OS":"5","UserAgent":"6","WebsiteCode":"7","ArticleId":"8","ATitle":"what thing \"nothing\" show","CateAlias":"10","LikeStatus":"11","TimeStamp":1352256727062,"_likeArticleGUId":"1","websiteCode":"7","likeStatus":"11","userID":"2","userName":"3","ip":"4","os":"5","userAgent":"6","articleID":"8","aTitle":"what thing \"nothing\" show","cateAlias":"10","timeStamp":1352256727062}
向我显示此问题中发生了什么?