最近做项目做到关于java json解析的部分记录一下 方便以后用到。。。。
废话少说贴代码。
String url="http://。。。。。。。。。";
StringBuffer json = new StringBuffer();
String strjson;
StringBuffer indexStrBuf = new StringBuffer();
try {
这都通过是读文件的固定格式。。。。
URL urlobj=new URL(url);
URLConnection uc = urlobj.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String inputLine=null;
while ((inputLine = in.readLine())!=null){
json.append(inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
strjson=json.toString();
//呵呵。。。因为返回的数据是jsonp格式 为了去掉 恶心的头部信息,我使用的是强大的正则表达式
Pattern pattern = Pattern.compile("\\bdoc\".*");//正则表达式
Matcher matcher = pattern.matcher(strjson); //你需要对它使用正则表达式的字符串
while (matcher.find()) {
strjson=matcher.group(); //其实应该存储到一个数组,或者使用stringbuffer里面但是,因为我的数据只有一条 所以我就懒得管了
}
System.out.println(strjson);
strjson=strjson.substring(5, strjson.length()-3);//呵呵还是为了处理不规整的json字符串
System.out.println(strjson);
//下面开始解析json字符串
JSONArray jsonarr=null;
JSONObject jsonobj=null;
try {
jsonarr=new JSONArray(strjson);
int i;
int len=jsonarr.length();
if(len>5)len=5;
for (i = 0; i < len ;i++) {
jsonobj= jsonarr.getJSONObject(i);
//下面这些都是根据需求去转的
String title=jsonobj.getJSONObject("item").getJSONObject("display").getString("title");
String pic=jsonobj.getJSONObject("item").getJSONObject("display").getJSONObject("thumbnails").getString("thumbnail");
String link=jsonobj.getJSONObject("item").getJSONObject("display").getString("url");
String price=jsonobj.getJSONObject("item").getJSONObject("display").getJSONObject("prices").getJSONObject("price").getString("value");
String discount=jsonobj.getJSONObject("item").getJSONObject("display").getString("discount");
String orlprice;
if(!"0".equals(discount)){
double prc=Double.valueOf(price);
double dis=Double.valueOf(discount);
double orlprc=prc/dis;
orlprice=((int)Math.rint(orlprc))+"";
}else{
orlprice=price;
}
discount=String.format("%.1f", Double.valueOf(discount)*10);
String baoyou;
if(jsonobj.toString().indexOf("free_ship")!=-1){
baoyou=jsonobj.getJSONObject("item").getJSONObject("display").getString("free_ship");
}else{
baoyou="0";
}
String list = "[\"" + title + "\",\"" + pic + "\",\"" + link + "\",\"" + price + "\",\"" + orlprice + "\",\"" + discount + "\",\"" + baoyou + "\"],";
indexStrBuf.append(list);
}
} catch (JSONException e) {
e.printStackTrace();
}
String liststr=indexStrBuf.toString();
int length=liststr.length();
liststr=liststr.substring(0, length-1);
最后就是转换成我想要的json了 ,搞定
String jsonstr="{desc:{title:0,pic:1,link:2,price:3,orlprice:4,discount:5,baoyou:6},list:[" + liststr+ "]}";
System.out.println(jsonstr);