1. 程式人生 > >java實現json檔案的讀取和解析

java實現json檔案的讀取和解析

	<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <
artifactId>
fastjson</artifactId> <version>1.2.37</version> </dependency> import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import lombok.Data; import org.apache.commons.io.FileUtils; import org.springframework.core.io.ClassPathResource;
import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; public
class MainApplication { public static Map<String, List<KeyValue>> map = new ConcurrentHashMap<>(28); public static void main(String[] args) throws IOException { String value = getValueForKeyAndId("channel", 1); System.out.println(value); List<String> strings = getValuesForKey("channel"); System.out.println(strings); } /** * 通過key 獲取所有value值 * @param key * @return * @throws IOException */ public static List<String> getValuesForKey(String key) throws IOException { List<KeyValue> list = getKeyValues(key); if (CollectionUtils.isEmpty(list)) {return null;} List<String> valueStrings = list.stream().map(s -> s.getValue()).collect(Collectors.toList()); return valueStrings; } /** * 通過key和id獲取value值 * @return */ public static String getValueForKeyAndId(String key,Integer id) throws IOException { List<KeyValue> list = getKeyValues(key); if (CollectionUtils.isEmpty(list)) {return null;} for (KeyValue keyValue : list) { if (keyValue.getId() == id) { return keyValue.getValue(); } } return null; } public static List<KeyValue> getKeyValues(String key) throws IOException { if (StringUtils.isEmpty(key)){return null;} if (CollectionUtils.isEmpty(map)) { readJsonData(); } List<KeyValue> list = map.get(key); return list; } /** * 讀取檔案資料加入到map快取中 * @throws IOException */ public static void readJsonData() throws IOException { ClassPathResource resource = new ClassPathResource("adConfig.json"); File file = resource.getFile(); String jsonString = FileUtils.readFileToString(file); JSONObject jsonObject = JSONObject.parseObject(jsonString); Set<String> keySet = jsonObject.keySet(); for (String s : keySet) { String stringArray = jsonObject.getJSONArray(s).toJSONString(); List<KeyValue> keyValues = JSONArray.parseArray(stringArray, KeyValue.class); map.put(s, keyValues); } } @Data static class KeyValue{ private int id; private String value; } }

在這裡插入圖片描述