JSON-JSON字符串转换成JSON对象、JSON对象数组、java实体类以及保存到List列表中

此页面是否是列表页或首页?未找到合适正文内容。

JSON-JSON字符串转换成JSON对象、JSON对象数组、java实体类以及保存到List列表中

标签:字符串百度ring对象httppost新华outfont

处理JSON字符串时,一直出错,写个样例后发现原来是没有弄清楚数据的格式问题。

实现的是 JSONString 转换成java对象 或是 list列表

实例类 News

package lyx.entity;

/**
* @author lyx
*
* 2015-8-10上午10:14:38
*
*
*新闻类
*/
public class News {

/**
* 日期
*/
private String date;

/**
* 链接
*/
private String link;
/**
* 标题
*/
private String title;

public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}

}

測试类:

package test;

import java.util.ArrayList;
import java.util.List;
import com.pom.lyx.entity.News;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class Test {

/**
* @param args
*/
public static void main(String[] args)
{
String str_news=\”[{‘date‘:‘2015-08-10 14:20:34‘,‘link‘:‘http://news.baidu.com/n?cmd=2&class=hongguan&page=http://news.xinhuanet.com/finance/2015-08/10/c_128112246.htm&cls=hongguan‘,‘title‘:‘发改委:尽快上报碳排放权交易管理条例 ――百度新闻搜索‘},\” +
\”{‘date‘:‘2015-08-10 14:13:22‘,‘link‘:‘http://news.xinhuanet.com/finance/2015-08/10/c_128112246.htm‘,‘title‘:‘发改委:尽快上报碳排放权交易管理条例-新华网‘},\” +
\”{‘date‘:‘2015-08-10 14:02:08‘,‘link‘:‘http://guba.eastmoney.com/news,600271,193716538.html‘,‘title‘:‘期待信心修复 14股潜伏现最佳时点‘},\” +
\”{‘date‘:‘2015-08-10 14:00:42‘,‘link‘:‘http://www.escn.com.cn/news/show-259795.html‘,‘title‘:‘外媒称中国欲将“APEC蓝”变常态‘}]\”;

//将JSON字符串转换成JSONArray
JSONArray array_news =new JSONArray();
array_news = JSONArray.fromObject(str_news);

//JSONArray -> JSONObject ->News ->List
List<News> newsList1 =new ArrayList<News>();
for (int i = 0; i < array_news.size(); i++) {
//JSONObject对象
JSONObject jsonObj =(JSONObject) array_news.get(i);

//依据key获取相应的值
System.out.println(jsonObj.getString(\”title\”));
//将JSONObject对象转换成实体类后加入到List列表中
newsList1.add((News) JSONObject.toBean(jsonObj ,News.class));
System.out.println(newsList1.get(i).getTitle()+\”:\”+newsList1.get(i).getLink());
}

//JSONArray -> List
@SuppressWarnings(\”unchecked\”)
//将JSONArray转换成List列表
List<News> newsList =(List<News>) JSONArray.toCollection(array_news, News.class);
for (News news : newsList) {
System.out.println(news.getDate()+\”:\”+news.getTitle()+\”:\”+news.getLink());
}
}
}

上面实现的是 JSONString 转换成java对象 或是 list列表

JSON-JSON字符串转换成JSON对象、JSON对象数组、java实体类以及保存到List列表中

标签:字符串百度ring对象httppost新华outfont

原文地址:http://www.cnblogs.com/jhcelue/p/6883217.html

作者: 老毛桃

为您推荐

返回顶部