Json
public int add(String name) throws IOException { String jsonStr = new String(Files.readAllBytes(Paths.get("/Users/zhangcheng/Downloads/"+name))); Map<String, String> map = new HashMap<>(); JSONObject respJson = JSONObject.parseObject(jsonStr, Feature.OrderedField); for (Map.Entry<String, Object> entry : respJson.entrySet()) { JsonOne jsonOne = new JsonOne(); String key = entry.getKey(); Object value = entry.getValue(); jsonOne.setKeyName(key); jsonOne.setValueName((String) value); jsonOneService.save(jsonOne); map.put(key, String.valueOf(value)); } return map.size(); }
Properties
由于Properties本身的构造方法会改变文件属性位置,所以我们需要重写Properties类 重写类如下:OrderedProperties
public class OrderedProperties extends Properties { private static final long serialVersionUID = -4627607243846121965L; private final LinkedHashSet<Object> keys = new LinkedHashSet<Object>(); public Enumeration<Object> keys() { return Collections.<Object> enumeration(keys); } public Object put(Object key, Object value) { keys.add(key); return super.put(key, value); } public Set<Object> keySet() { return keys; } public Set<String> stringPropertyNames() { Set<String> set = new LinkedHashSet<String>(); for (Object key : this.keys) { set.add((String) key); } return set; } }
然后实现如下:
@GetMapping("/properties") public int addx(String name) throws IOException { Properties props = new OrderedProperties(); props.load(new FileReader("/Users/zhangcheng/Downloads/"+name)); // 将properties转换为LinkedHashMap Map<String, String> data = new LinkedHashMap<>(); for (String key : props.stringPropertyNames()) { JsonOne jsonOne = new JsonOne(); String value = props.getProperty(key); jsonOne.setKeyName(key); jsonOne.setValueName(value); jsonOneService.save(jsonOne); data.put(key, props.getProperty(key)); } return data.size(); }