服务器端与客户端使用Json进行数据交互

本文展示了如何在服务器端使用Java将对象转换为JSON并传递到客户端,以及客户端如何通过HTTP请求获取JSON数据并解析为对象。服务器端通过设置响应头防止数据缓存,并使用JSONArray将对象列表转化为JSON字符串。客户端则使用HttpClient发起GET请求,获取JSON数据后通过Gson库反序列化为对象列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

服务器端:

引入相应的包:json-lib-2.2-jdk15.jar

Action:

public String findAll() throws IOException{

List<News> news = newsService.findAll();

//把java 对象列表转换为json对象数组,并转为字符串

JSONArray array = JSONArray.fromObject(news);

//将数据输送到后台,设置数据编码格式和防止后台自动缓存

this.getResponse().setContentType("text/html; charset=utf-8");
this.getResponse().setHeader("Cache-Control", "no-cache");
this.getResponse().getWriter().print(array);
return null;
}

客户端:

public class HttpUtil {
// 通过指定的网络地址获得图片
public static Bitmap getBitmapFromUrl(String bmpUrl) {
URL url;
try {
url = new URL(bmpUrl);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// 将与指定地址建立的输入流转成图片
Bitmap bmp = BitmapFactory.decodeStream(is);
return bmp;
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

// 从指定服务器地址获得返回的Json数据,并转成字符串
public static String getStringFromUrl(String url) {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
// 向指定服务器地址发出get请求
try {
HttpResponse response = client.execute(httpGet);
String result = EntityUtils.toString(response.getEntity());
return result;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}


public class NewsService {
private final String baseUrl = "http://169.254.44.91:8080/News";
// 将服务器返回的Json数据,转成List<NewsInfo>对象
public List<News> getNewsInfo() {
String result = HttpUtil.getStringFromUrl(baseUrl + "/newsAction!findAll.action");
Log.i("result", result);
List<News> meal = new Gson().fromJson(result,new TypeToken<List<News>>() {}.getType());
Log.i("标题:", meal.get(0).getTitle());
for (News meals : meal) {
meals.setImage("http://169.254.44.91:8080/News/images/"+ meals.getImage());
}
return meal;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值