E G*_*E G 4 java arraylist jackson
我将所有静态数据存储在JSON文件中。该JSON文件最多有行1000。如何获取所需的数据而不将所有行存储为ArrayList?
我的代码,我现在正在使用,我想提高它的效率。
List<Colors> colorsList = new ObjectMapper().readValue(resource.getFile(), new TypeReference<Colors>() {});
for(int i=0; i<colorsList.size(); i++){
if(colorsList.get(i).getColor.equals("Blue")){
return colorsList.get(i).getCode();
}
}
Run Code Online (Sandbox Code Playgroud)
是否可以?我的目标是在不使用ArrayList. 有没有办法让代码变成这样?
Colors colors = new ObjectMapper().readValue(..."Blue"...);
return colors.getCode();
Run Code Online (Sandbox Code Playgroud)
资源.json
[
...
{
"color":"Blue",
"code":["012","0324","15478","7412"]
},
{
"color":"Red",
"code":["145","001","1","7879","123984","89"]
},
{
"color":"White",
"code":["7","11","89","404"]
}
...
]
Run Code Online (Sandbox Code Playgroud)
颜色.java
class Colors {
private String color;
private List<String> code;
public Colors() {
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public List<String> getCode() {
return code;
}
public void setCode(List<String> code) {
this.code = code;
}
@Override
public String toString() {
return "Colors{" +
"color='" + color + '\'' +
", code=" + code +
'}';
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下创建POJO类是一种浪费,因为我们不使用整个结果List<Colors>,而只使用一个内部属性。为了避免这种情况,我们可以使用本机类型JsonNode和ArrayNode数据类型。我们可以JSON使用readTree方法读取,迭代数组,找到给定的对象,最后转换内部code数组。它可能如下所示:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = new ObjectMapper();
ArrayNode rootArray = (ArrayNode) mapper.readTree(jsonFile);
int size = rootArray.size();
for (int i = 0; i < size; i++) {
JsonNode jsonNode = rootArray.get(i);
if (jsonNode.get("color").asText().equals("Blue")) {
Iterator<JsonNode> codesIterator = jsonNode.get("code").elements();
List<String> codes = new ArrayList<>();
codesIterator.forEachRemaining(n -> codes.add(n.asText()));
System.out.println(codes);
break;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码打印:
[012, 0324, 15478, 7412]
Run Code Online (Sandbox Code Playgroud)
这个解决方案的缺点是我们将整个加载JSON到内存中,这对我们来说可能是一个问题。让我们尝试使用Streaming API它来做到这一点。使用起来有点困难,你必须知道你的JSON有效负载是如何构造的,但它是code使用Jackson. 下面的实现很幼稚,不能处理所有可能性,因此您不应该依赖它:
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
System.out.println(getBlueCodes(jsonFile));
}
private static List<String> getBlueCodes(File jsonFile) throws IOException {
try (JsonParser parser = new JsonFactory().createParser(jsonFile)) {
while (parser.nextToken() != JsonToken.END_OBJECT) {
String fieldName = parser.getCurrentName();
// Find color property
if ("color".equals(fieldName)) {
parser.nextToken();
// Find Blue color
if (parser.getText().equals("Blue")) {
// skip everything until start of the array
while (parser.nextToken() != JsonToken.START_ARRAY) ;
List<String> codes = new ArrayList<>();
while (parser.nextToken() != JsonToken.END_ARRAY) {
codes.add(parser.getText());
}
return codes;
} else {
// skip current object because it is not `Blue`
while (parser.nextToken() != JsonToken.END_OBJECT) ;
}
}
}
}
return Collections.emptyList();
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码打印:
[012, 0324, 15478, 7412]
Run Code Online (Sandbox Code Playgroud)
最后我需要提到JsonPath解决方案,如果您可以使用其他库,该解决方案也可能很好:
import com.jayway.jsonpath.JsonPath;
import net.minidev.json.JSONArray;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
public class JsonPathApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
JSONArray array = JsonPath.read(jsonFile, "$[?(@.color == 'Blue')].code");
JSONArray jsonCodes = (JSONArray)array.get(0);
List<String> codes = jsonCodes.stream()
.map(Object::toString).collect(Collectors.toList());
System.out.println(codes);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码打印:
[012, 0324, 15478, 7412]
Run Code Online (Sandbox Code Playgroud)