这取决于你的身材有多大
JSON。如果可以将其加载到内存,则可以使用最简单的方法: 解决方案1:
POJO类:
class CoordinatesContainer { private double[][][] coordinates; public double[][][] getCoordinates() { return coordinates; } public void setCoordinates(double[][][] coordinates) { this.coordinates = coordinates; } @Override public String toString() { StringBuilder builder = new StringBuilder(1024); for (double[] arrayItem : coordinates[0]) { builder.append(Arrays.toString(arrayItem)); builder.append(", "); } return builder.toString(); }}
用法:
ObjectMapper mapper = new ObjectMapper();CoordinatesContainer coordinatesContainer = mapper.readValue(json, CoordinatesContainer.class);System.out.println(coordinatesContainer);
上面的程序打印:
[-72.943068, 45.842298], [-72.943075, 45.841859]
解决方案2:
但是,如果您
JSON的确很大,并且无法将其加载到内存中,则应考虑Jackson Streaming
API。在这种情况下,您不应创建POJO类并尝试按“节点”来处理每个元素“节点”:
import java.io.File;import java.io.IOException;import java.math.BigDecimal;import java.util.Arrays;import com.fasterxml.jackson.core.JsonFactory;import com.fasterxml.jackson.core.JsonParser;import com.fasterxml.jackson.core.JsonToken;public class JsonProgram { public static void main(String[] args) throws IOException { File json = new File("/x/data.json"); JsonFactory jsonFactory = new JsonFactory(); JsonParser parser = jsonFactory.createParser(json); // Skip all elements to first array while (parser.nextToken() != JsonToken.START_ARRAY) { } parser.nextToken(); // First level while (parser.nextToken() != JsonToken.END_ARRAY) { // Skip inner start array element parser.nextToken(); System.out.println(); System.out.println("NEXT ARRAY NODE"); BigDecimal first = parser.getDecimalValue(); // Go to second value parser.nextToken(); BigDecimal second = parser.getDecimalValue(); // Skip inner end array element parser.nextToken(); // Handle array item System.out.println("First: " + first.toString()); System.out.println("Second: " + second.toString()); } }}
上面的程序打印:
NEXT ARRAY NODEFirst: -72.943068Second: 45.842298NEXT ARRAY NODEFirst: -72.943075Second: 45.841859
在我的示例中,我使用
Jackson了
2.2.3版本。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)