java對象轉字元串
發布時間: 2023-06-26 22:56:01
Ⅰ java ObjectMapper 將對象轉換成json字元串問題
先給你一個正確的方法:
1,把bean裡面的get方法上面的格式去掉
我的代碼如下:
privateTimestamptime;
publicTimestampgetTime(){
returntime;
}
publicvoidsetTime(Timestamptime){
this.time=time;
}
測試方法:
publicstaticvoidmain(String[]args)throwsJsonProcessingException,ParseException{
Timestamptimestamp=newTimestamp(System.currentTimeMillis());
AccountInfoaccountInfo=newAccountInfo();
accountInfo.setTime(timestamp);
ObjectMappermapper=newObjectMapper();
mapper.setDateFormat(newSimpleDateFormat("yyyy-MM-ddhh:mm:ss"));
Strings=mapper.writeValueAsString(accountInfo);
System.out.println(s);
longtime=DateUtils.parseDate("1987-06-0400:00:001","yyyy-MM-ddhh:mm:ss").getTime();
Stringdate=DateUtils.parseDate("1987-06-0400:00:01","yyyy-MM-ddhh:mm:ss").toString();
System.out.println(date);
timestamp=Timestamp.valueOf("1987-06-0400:00:00");
System.out.println(timestamp);
accountInfo=newAccountInfo();
accountInfo.setTime(timestamp);
mapper=newObjectMapper();
mapper.setDateFormat(newSimpleDateFormat("yyyy-MM-ddhh:mm:ss"));
s=mapper.writeValueAsString(accountInfo);
System.out.println(s);
}
輸出結果:
{"openId":null,"token":null,"ip":null,"account":null,"phone":null,"email":null,"platformType":0,"time":"2018-10-1601:27:16"}
ThuJun0400:00:01CDT1987
1987-06-0400:00:00.0
{"openId":null,"token":null,"ip":null,"account":null,"phone":null,"email":null,"platformType":0,"time":"1987-06-0412:00:00"}
不過這里有一個小問題,因為你是使用的yyyy-MM-dd hh:mm:ss 格式,而hh表示按12小時計時,所以1987-06-04 00:00:00會在json中表示為1987-06-04 12:00:00,你可以換成yyyy-MM-dd HH:mm:ss按24小時計進即可。
Ⅱ java 怎麼將對象轉化為字元串數組
不懂你說什麼,不是什麼對象都能轉成字元串數組的,你是不是說的list轉數組
List<ResourceType> resourceTypes=resourceTypeService.findAll();
ResourceType[] resourceTypeArray=(ResourceType[]) resourceTypes.toArray();
Ⅲ java中如何將對象轉成json格式字元串
用Gson轉換就行了,需要下載jar包
例子:
Personperson=newPerson();
Gsongson=newGson();
Stringjson=gson.toJson(person);
熱點內容