赞
踩
模板类
/* 商家,设计商家模型 */ public class Merchant { //商家名称 private String name; //商家地址 private String address; //商家菜品 private Dishes[] dishes; //经度 private double lon; //纬度 private double lat; //距离 private double distance; private String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Dishes[] getDishes() { return dishes; } public void setDishes(Dishes[] dishes) { this.dishes = dishes; } public double getLon() { return lon; } public void setLon(double lon) { this.lon = lon; } public double getLat() { return lat; } public void setLat(double lat) { this.lat = lat; } public String getId() { return id; } public void setId(String id) { this.id = id; } public double getDistance() { return distance; } public void setDistance(double distance) { this.distance = distance; } }
转换为 json 数据
//存储 json 数据 public class JsonTest { public static void main(String[] args) { ObjectMapper objectMapper = new ObjectMapper(); // 转换数据为 json 数据 Merchant merchant = new Merchant(); merchant.setName("麦当劳"); String jsonContent = null; Merchant merchant1 = null; File file = new File("./demo.json"); try{ jsonContent = objectMapper.writeValueAsString(merchant); System.out.println(jsonContent); merchant1 = objectMapper.readValue( jsonContent, Merchant.class); System.out.println(merchant1.getName()); objectMapper.writeValue(file, merchant); }catch (JsonProcessingException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); } } }
结果
{"name":"麦当劳","address":null,"dishes":null,"lon":0.0,"lat":0.0,"distance":0.0,"id":null}
读取 json + 筛选
[ { "id": null, "name": "麦当劳", "distance": 100 }, { "id": "2", "name": "麦乐基", "distance": 200 }, { "id": "3", "name": "肯德基", "distance": 150 }, { "id": "4", "name": "必胜客", "distance": 10 }, { "id": "5", "name": "必胜客", "distance": 103 } ]
public class JsonTest { public static void main(String[] args) { ObjectMapper objectMapper = new ObjectMapper(); // 读取 json 文件,转化为 list 格式 List<Merchant> merchantList = null; try{ merchantList = objectMapper.readValue( new File("./demo.json"), new TypeReference<List<Merchant>>(){}); }catch (IOException e){ e.printStackTrace(); } // 执行 stream 过滤 List<Merchant> merchantList1 = merchantList.stream(). filter(m ->m.getName().indexOf("必胜客") >= 0).collect(Collectors.toList()); for (Merchant merchant : merchantList1){ System.out.println(merchant.getId()); System.out.println(merchant.getName()); System.out.println(merchant.getDistance()); } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。