gpt4 book ai didi

java - 如何使用Java循环输入Json?

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:57 26 4
gpt4 key购买 nike

我有一个 Json 数组文件,它有多个数据。正如您在下面的数据中看到的,您会多次注意到 timeLastUpdate 。当我用Java编译时,我得到的输出只是JSON中的第一次LastUpdate。我想要 Java 中显示的所有 timeLastUpdate。我该怎么做?

数据示例:

 [
{
"mmsi": "253336000",
"status": "RESTRICTED_MANEUVERABILITY",
"courseOverGround": 7.9,
"timeLastUpdate": 1464545149000,
"
},
{
"mmsi": "253336000",
"timeLastUpdate": 1464545209000,
"destination": "ZEEBRUGGE",
},
]

Java 代码:

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.DeserializationFeature;
import java.io.File;
import java.net.URL;
import java.io.IOException;

public class ShipMain {

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

File jsonFile2 = new File("shiphistory.json");

ShipData shiphistory = null;

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

shiphistory = mapper.readValue(jsonFile2, ShipData.class);
System.out.println("______________ History_________");
System.out.println("Ship Name : " + shiphistory.getName());
System.out.println("Ship MMSI : " + shiphistory.getMmsi());
System.out.println("Ship Type : " + shiphistory.getShipType());
System.out.println("Ship Departure : " + shiphistory.getTimeLastUpdate());


}

}

最佳答案

要使用 ObjectMapper 解析 JSON 数组,您可以查看所选答案 here 。基本上,您的代码应该如下所示:

ObjectMapper mapper = new ObjectMapper(); 
ShipData[] shipDataArray = mapper.readValue(jsonFile2, ShipData[].class);
//then you can look through the array
System.out.println("______________ History_________");
for(int x=0; x < shipDataArray.length(); x++){
shiphistory = shipDataArray[x];
System.out.println("Ship Name : " + shiphistory.getName());
System.out.println("Ship MMSI : " + shiphistory.getMmsi());
System.out.println("Ship Type : " + shiphistory.getShipType());
System.out.println("Ship Departure : " + shiphistory.getTimeLastUpdate());
//just a separating line (not necessary - just to separate the shipdata items
System.out.println("-----------------------------------------------------");
}

尝试一下,如果这对您有帮助,请告诉我们。

关于java - 如何使用Java循环输入Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37533080/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com