<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;
}
}
java实现json文件的读取和解析
猜你喜欢
转载自blog.csdn.net/weixin_38799368/article/details/83186340
今日推荐
周排行