這取決於你的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 feature。在這種情況下,你不應該創建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 NODE
First: -72.943068
Second: 45.842298
NEXT ARRAY NODE
First: -72.943075
Second: 45.841859
在我的例子,我在2.2.3
版本中使用Jackson
。
這將是一個包含'double [] [] []'的對象。 – SLaks
[gson](https://code.google.com/p/google-gson/)? –
請參閱http://stackoverflow.com/questions/1395551/convert-a-json-string-to-object-in-java –