public class Product { public String Id; public String ProductName; public Product(String id,String productName) { this.Id=id; this.ProductName=productName; } public static ArrayList<Product> parseList(String response) { ArrayList<Product> products=new ArrayList<Product>(); JSONArray arrayProduct = null; try { arrayProduct = new JSONArray(response); for (int i=0;i<arrayProduct.length();i++){ String id= arrayProduct.getJSONObject(i).getString("id"); String name= arrayProduct.getJSONObject(i).getString("name"); products.add(new Product(id,name)); } } catch (JSONException e) { e.printStackTrace(); } return products; } }
private Handler mHandler = new Handler(Looper.getMainLooper()); private void readNetJson() { AppUpdater.getInstance().getNetManager().get(APP_VERSION_URL, new INetCallBack() { @Override public void success(String response) { final ArrayList<Product> products = Product.parseList(response); if (products == null) { mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "服务器返回版本信息错误", Toast.LENGTH_SHORT).show(); } }); } //弹框显示版本信息 mHandler.post(new Runnable() { @Override public void run() { try { saveSingleJson(products); } catch (IOException e) { e.printStackTrace(); } } }); } @Override public void failed(Throwable throwable) { mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "网络错误,更新版本失败", Toast.LENGTH_SHORT).show(); } }); } }, MainActivity.this); }
private void saveSingleJson(ArrayList<Product> products) throws IOException { Toast.makeText(this, "保存独立Json文件", Toast.LENGTH_LONG).show(); //json数据 //products=new ArrayList<Product>(); //products.add(new Product("96356170", "明月端0001")); //打开要写入的json文件 FileOutputStream fos =new FileOutputStream(jsonFile); //创建JsonWrite对象 JsonWriter writer =new JsonWriter(new OutputStreamWriter(fos, "utf-8")); writer.setIndent(" "); writer.beginArray(); for (Product product:products){ writer.beginObject(); writer.name("id").value(product.Id); writer.name("name").value(product.ProductName); writer.endObject(); } writer.endArray(); writer.close(); }
private void readSingleJson() throws IOException { FileInputStream fis =new FileInputStream(jsonFile); JsonReader reader =new JsonReader(new InputStreamReader(fis,"utf-8")); products =new ArrayList<Product>(); reader.beginArray(); while (reader.hasNext()){ String id = ""; String name = ""; reader.beginObject(); while (reader.hasNext()) { String field = reader.nextName(); if (field.equals("id")){ id = reader.nextString(); }else if (field.equals("name")){ name = reader.nextString(); }else{ reader.skipValue(); } } reader.endObject(); products.add(new Product(id, name)); } reader.endArray(); reader.close(); if (products != null) { ttvwJson.setText(products.size()+""); } }
原文:https://www.cnblogs.com/lujie0601/p/14858600.html