package com.bcj.Test;
import com.google.gson.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
public class Test {
public static void main(String[] args) throws IOException {
JsonParser parse =new JsonParser(); //创建json解析器
try {
JsonObject json=(JsonObject) parse.parse(new FileReader("src/info.json")); //创建jsonObject对象
JsonObject result = json.get("showapi_res_body").getAsJsonObject();
if (result.get("img") != null){//如果Json返回的img参数不为空,就把图片下载到本地
String url = result.get("img").getAsString();
String path="F:/test/pic.jpg";
downloadPicture(url,path);
System.out.println("Json文件中存在图片,图片下载成功,请到F:/test查看");
}
System.out.println("商品分类:"+result.get("goodsType").getAsString());
System.out.println("原产地:"+result.get("ycg").getAsString());
System.out.println("商标/品牌名称:"+result.get("trademark").getAsString());
System.out.println("厂商:"+result.get("manuName").getAsString());
System.out.println("规格:"+result.get("spec").getAsString());
} catch (JsonIOException e) {
e.printStackTrace();
} catch (JsonSyntaxException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static void downloadPicture(String urlList,String path) {
URL url = null;
try {
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}