java工具类11.1之Gson,Jsonobject,中文乱码,接口

哎,上一周没有总结,主要是做了Gson数据转换,其实就是从一个接口拿出来json数据中转一下在传给前台。

一。首先maven依赖



org.codeartisans
org.json
20131017



com.google.code.gson
gson
2.2.4



commons-codec
commons-codec
1.5

二.从接口取数据,这里从接口中拿数据分两种情况;

1.这个接口是Get请求
代码:

// 把资源转换成String,再转换成jsonobject,name:为返回的jsonobject起一个名字
public static JSONObject getUrl(String source,String name){

StringBuilder builder = new StringBuilder();
try {
// source = URLEncoder.encode(source);
System.out.println("source----"+source);
URL url = new URL(source);
URLConnection uc = url.openConnection();
// uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream(),"UTF-8"));
String line = null;
while((line = br.readLine())!=null){
// line = new String(line.getBytes("utf-8"), "utf-8");
builder.append(line);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String message = builder.toString();
message = judgeBrace(message,name);
JSONObject jsonObject = new JSONObject(message);
return jsonObject;
}

2.这个接口是post请求

// 把资源转换成String,再转换成jsonobject,name:为返回的json起名字
public static JSONObject getPostUrl(String source,String name){

StringBuilder builder = new StringBuilder();
try {
URL url = new URL(source);
URLConnection uc = url.openConnection();
HttpURLConnection httpcoon = (HttpURLConnection) url.openConnection();
httpcoon.setDoOutput(true);
httpcoon.setDoInput(true);
httpcoon.setRequestMethod("POST");
InputStream is = httpcoon.getInputStream();
uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
String line = null;
while((line = br.readLine())!=null){
// line = new String(line.getBytes("utf-8"), "utf-8");
builder.append(line);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String message = builder.toString();
// System.out.println(message.equals("[]"));
message = judgeBrace(message,name);
JSONObject jsonObject = new JSONObject(message);
return jsonObject;
}

3.然后有一个judgeBrace()的方法,

是我用来判断从接口中取出来的数据有没有{}包围,还是只是简单的【】包围的数组,

如果是{},传入的参数name就没用了,如果是【】会返回这样的数据{name:【】},就是要给这个返回的json定义一个名字而已。

代码:

// brace大括号,把从接口中读出来json数据没有{}包围,没有名字的,用{}包围并起一个名字
public static String judgeBrace(String message,String name){

StringBuffer sb = new StringBuffer();
int begin = message.indexOf("{");
// System.out.println("begin::"+begin);
if(begin == 0){
sb.append(message);
}else{
sb.append("{");
sb.append(name+":");
sb.append(message);
sb.append("}");
}
return sb.toString();
}


这样就ok了,source格式:http://api.公司域名.com/api/v2/brand/list

期间使用的话会出现异常; java.io.FileNotFoundException: http://api.s。。。。。。。 org.json.JSONException: Missing value at 11 [character 12 line 1]

就是传入的资源url找不到,可能是因为本来就把url定义错了,或者是openConnection那里打开流出错了,具体的现在也忘了怎么解决了,google呗....基本上以上两种请求搞的定。。


三:拿出来jsonObject后要转换成自己对应的List了或entity了

1.首先定义实体类,看接口里面的数据,然后创建出自己的实体类:
例如店铺信息;
public class MyShop {

private int api_type;
private String image;
private String api_url_method;
private int height;
private int width;
private int brand_id;
private String api_url;
private int like;
private Boolean follow;
private String title;
private List banner;
}
然后生成get。set方法和toString()方法

2.把接口里数据转换成对应类型

public static List getAllShop(JSONObject jsonObject){
// 已测试可用
List shops = new ArrayList();
JSONArray array = jsonObject.getJSONArray("shop");
Gson gson = new Gson();
shops = gson.fromJson(array.toString(), new TypeToken>() {
}.getType());
return shops;
}

搞定!

具体的json转换成Bean,转换成List;又或List,Bean转换成jsonObject,

google上一搜Gson一大推,用的时候在找!

附个简单的Gson使用连接:

http://blog.csdn.net/lk_blog/article/details/7685169


四:最后一步!创建自己的接口,封装好数据:

1.自己的工具类中创建此方法
// 分类导航
public static String getAllSiderBar(){

String url = Http.Tablet.siderBar;
JSONObject jsonObject = getUrl(url, "siderBar");
JSONArray array = jsonObject.getJSONArray("siderBar");
Gson gson = new Gson();
List list = gson.fromJson(array.toString(), new TypeToken>() {
}.getType());

String api_url = null;
for(SiderbarModel element:list){
List banners = element.getList();
for(Banner ban:banners){
url = ban.getUrl();
String close = CloseUrl.close(url);
ban.setUrl(close);
}
}
String all = gson.toJson(list);
return all;
}

2.在控制器中定义接口,返回json数据
@RequestMapping(value = "/siderBar", method = RequestMethod.GET)
public 
@ResponseBody
String getSiderBar(SitePreference sitePreference, Device device,
Model model, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, HttpSession session) {
System.out.println("siderBar");
String siderBar = JsonUtil.getAllSiderBar();
return siderBar;
}

这样启动程序,在网址中输入 “http://ip:8080/项目名称/控制器名/接口名  就可以返回json数据了!

在这里必须要注意这行代码:String all = gson.toJson(list);只有这样才会返回json类型数据,具体什么原理就不晓得了。。


最后:一些小细节的处理问题

1.比如接口传参数为中文会乱码

接口中传过来key=中文;;;;而不是这种类型的“中文”,会乱码报错什么的,解决方法

byte[] temp=key.getBytes("iso8859-1");
key = new String(temp);

// 搜索
@RequestMapping(value = "/search", method = RequestMethod.POST)
public 
@ResponseBody
String getSearch(SitePreference sitePreference, Device device,
Model model, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, HttpSession session,
@RequestParam(value="keyword") String key,
@RequestParam(value="page",required=false,defaultValue="1")int page) {
System.out.println("keyword::"+key);
String goods = null;
if(key != null){
try {
byte[] temp=key.getBytes("iso8859-1");
key = new String(temp);
goods = JsonUtil.getSearch(key,page);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return goods;
}




你可能感兴趣的:(java的一些类,异常处理)