【发布时间】:2017-06-12 20:38:19
【问题描述】:
我试图读取 JSON 文件并将其转换为数组,但在读取 JSON 文件后从数组中获取空值。我正在为 ShipDetail 类使用默认构造函数。
BufferedReader detailReader = new BufferedReader( new FileReader(shipDetails));
// Buffered passed to convert json array to java array
ShipDetail[] shipDetail = gson.fromJson(detailReader, ShipDetail[].class );
System.out.println( shipDetail[0].toString());
// Convert array to arrayList
ArrayList<ShipDetail> detailArray = new ArrayList<ShipDetail>(Arrays.asList(shipDetail));
JSON 文件:
[
{
"idmessage":"27301",
"idsession":"362",
"time_stamp_system":"2017-01-20 14:51:14",
"NMEA_string":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"processed":"1",
"MMSI":"0000000001",
"AIS_version":"0",
"IMO_number":"xxxxxxxxxx",
"callSign":"ODLK1",
"name":"ODLXJ KWW",
"type_of_ship_and_cargo":"0",
"bow_to_possition_unit":"212",
"stern_to_possition_unit":"71",
"port_to_possition_unit":"22",
"starboard_to_possitio_unit":"22",
"type_of_position_fixing_divice":"1",
"ETA":null,
"destination":"",
"last_static_draught":"0",
"DTE":"127"
}
]
ShipDetail 类:
public class ShipDetail {
private String IdMessage, IdSession, Time_Stamp_System, Nmea_String, Processed;
private String Mmsi, Ais_Version, Imo_Number, Callsign, Name, Type_Of_Ship_And_Cargo;
private String Bow_To_Position_Unit, Stern_To_Position_Unit, Port_To_Position_Unit, Starboard_To_Position_Unit,
Type_Of_Position_Fixing_Device;
private String Eta, Destination, Last_Ship_Draught, Dte;
public String getMmsi() {
return Mmsi;
}
public String toString() {
return "\n Id Message : " + IdMessage + "\n Id Session : " + IdSession + "\n Time Stam System : "
+ Time_Stamp_System + "\n NMEA String : " + Nmea_String + "\n Processed : " + Processed + "\n MMSI : "
+ Mmsi + "\n AIS Version : " + Ais_Version + "\n IMO Number : " + Imo_Number + "\n Call Sign : "
+ Callsign + "\n Name : " + Name + "\n Type Of Ship And Cargo : " + Type_Of_Ship_And_Cargo
+ "\n Bow To Position Unit : " + Bow_To_Position_Unit + "\n Stern To Position Unit : "
+ Stern_To_Position_Unit + "\n Port To Position Unit : " + Port_To_Position_Unit
+ "\n Starboard To Position Fixing Device : " + Starboard_To_Position_Unit
+ "\n Type Of Position Fixing Device : " + Type_Of_Position_Fixing_Device + "\n ETA : " + Eta
+ "\n Destination : " + Destination + "\n Last Ship Draught : " + Last_Ship_Draught + "\n DTE : " + Dte;
}
}
【问题讨论】:
-
你能显示json文件吗?还有 ShipDetail 的外观,它是否有构造函数、get 和 set 方法,是否重写了 toString 方法以便使用它?
-
我使用的是默认构造函数,并且我已经覆盖了 toString( ) 方法。
-
你还需要生成getter和setter。你的文件是
private。此外,在将事物直接映射到 Object 时,您需要使用 getter 和 setter,大多数库都需要它们。 -
和声明public而不是private一样吗?
-
没有。将 SQL 或 JSON 或 XML 映射到 java 对象的自定义库的实现正在寻找 GET 和 SET 方法。这就是它们的实施方式。他们会这样做:
object.setField1(someValue)而不是object.field1 = someValue。
标签: java arrays json arraylist gson