Json:javaBean轉為Json的兩種方式
阿新 • • 發佈:2019-01-27
<!--Json -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
package com.donews.data.kafkaoffset;
import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
/**
* 普通文章
*
* @author yuhui
*/
public class ArticleBean {
public String Url;
public String Title;
public String PublishTime;
public ArticleBean() {
Url = "";
Title = "";
PublishTime = "" ;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
Url = url;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getPublishTime() {
return PublishTime;
}
public void setPublishTime(String publishTime) {
PublishTime = publishTime;
}
//
@SuppressWarnings({ "unchecked", "rawtypes" })
public String toJson(){
Map map = new HashMap();
map.put( "Url",Url);
map.put( "Title",Title);
map.put( "PublishTime",PublishTime);
JSONObject jsonObject = JSONObject.fromObject(map);
return jsonObject.toString();
}
/**
* 返回json格式
* @return
*/
public String toJson2(){
return "{'"+"Url"+"':'"+getUrl()+"':'"+",'"+"Title"+"':'"+getTitle()+"'"+",'"+"PublishTime"+"':'"+getPublishTime()+"}";
}
public static void main(String args[]){
ArticleBean articleBean = new ArticleBean();
articleBean.Url="www.baidu.com";
articleBean.Title="百度";
articleBean.PublishTime="2015-10-11";
System.out.println(articleBean.toJson());
System.out.println(articleBean.toJson2());
}
}
結果展示:
{“Title”:”百度”,”PublishTime”:”2015-10-11”,”Url”:”www.baidu.com”}
{‘Url’:’www.baidu.com’:’,’Title’:’百度’,’PublishTime’:’2015-10-11}
如果您喜歡我寫的博文,讀後覺得收穫很大,不妨小額贊助我一下,讓我有動力繼續寫出高質量的博文,感謝您的讚賞!!!