문제가 있습니다. 다음 JSON이 있습니다.
[
{
"Id":"8",
"MasterAgentId":"0",
"LastAgentStrategyId":"16116488969159",
"BotState":"Active",
"Owner":"Andre",
"ExtraNotifiers":"",
"Exchange":"lava",
"DateTime":"2021-01-27 22:12:02",
"AgentStatus":"Enabled",
"ProtectiveOrdersEnabled":"yes",
"Sim_Progress":"100",
"Sim_DateTime":"2021-01-27 09:18:00",
"Sim_Coin":"BTC",
"Sim_Price":"31626.580000",
"Sim_Profit":"1216.04",
"Sim_Profit_Perc":"60.80",
"Sim_StartDateTime":"2019-01-01 00:00:00",
"LastAgentStrategyRun":"2020-12-19 17:40:30.531000"
}
]
보시다시피 JSON에 4 개의 DateTime이 있습니다. DateTime, Sim_DateTime, Sim_StartDateTime, LastAgentStrategyRun
이제 다음과 같은 클래스를 만들었습니다.
import java.time.LocalDateTime;
public class Agent {
private int Id;
private int MasterAgentId;
private long LastAgentStrategyId;
private AgentBotState BotState;
private String Owner;
private String ExtraNotifiers;
private AgentExchanges Exchange;
private LocalDateTime DateTime;
private AgentStatus AgentStatus;
private String ProtectiveOrdersEnabled;
private String Sim_Progress;
private String Sim_DateTime;
private String Sim_Coin;
private double Sim_Price;
private double Sim_Profit;
private double Sim_Profit_Perc;
private LocalDateTime Sim_StartDateTime;
private LocalDateTime LastAgentStrategyRun;
}
하지만 GSON을 사용하여 json을 역 직렬화 할 때 :
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<Agent>>() {}.getType();
ArrayList<Agent> agentList = new Gson().fromJson(jsonResponse, listType);
다음과 같은 오류가 발생합니다.
그러나 코드는 다음 오류와 함께 충돌합니다.
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 157 path $[0].DateTime
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson.fromJson(Gson.java:810)
at com.google.gson.Gson.fromJson(Gson.java:775)
at com.google.gson.Gson.fromJson(Gson.java:724)
at com.company.Main.main(Main.java:34)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 157 path $[0].DateTime
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:387)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:189)
... 9 more
이제 json에서 모든 날짜 시간을 제거하면 몇 가지 이상한 경고만으로 올바르게 구문 분석됩니다.
경고 : 잘못된 반사 액세스 작업이 발생했습니다. 경고 : com.google.gson.internal.bind.ReflectiveTypeAdapterFactory (file : / C : /Users/Alexander/.m2/repository/com/google/code/gson/에 의한 불법 반사 액세스) gson / 2.3.1 / gson-2.3.1.jar) 필드에 java.time.LocalDateTime.date 경고 : com.google.gson.internal.bind.ReflectiveTypeAdapterFactory의 관리자에게보고하는 것을 고려하십시오. 경고 : --illegal 사용 -access = warn은 추가 불법적 인 반사 액세스 작업에 대한 경고를 활성화합니다. 경고 : 모든 불법 액세스 작업은 향후 릴리스에서 거부됩니다.
객체에 대한 datetime 문자열을 어떻게 구문 분석하고 경고를 제거 할 수 있습니까?
추가로 다음 코드를 사용합니다.
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json, type, jsonDeserializationContext) -> {
Instant instant = Instant.ofEpochMilli(json.getAsJsonPrimitive().getAsLong());
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}).create();
Type listType = new TypeToken<ArrayList<Agent>>() {}.getType();
ArrayList<Agent> agentList = gson.fromJson(jsonResponse, listType);
이제이 오류가 발생합니다.
Exception in thread "main" java.lang.NumberFormatException: For input string: "2021-01-27 22:56:01"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
at java.base/java.lang.Long.parseLong(Long.java:707)
at java.base/java.lang.Long.parseLong(Long.java:832)
at com.google.gson.JsonPrimitive.getAsLong(JsonPrimitive.java:238)
at com.company.Main.lambda$main$0(Main.java:35)
at com.google.gson.TreeTypeAdapter.read(TreeTypeAdapter.java:58)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:103)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:196)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson.fromJson(Gson.java:810)
at com.google.gson.Gson.fromJson(Gson.java:775)
at com.google.gson.Gson.fromJson(Gson.java:724)
at com.company.Main.main(Main.java:40)
LocalDateTime을 등록해야합니다 : egreplace Gson gson = new Gson();
아래 코드를 참조하십시오.
Instant를 만드는 대신 날짜 포맷터를 사용하여 LocalDateTime을 구문 분석하도록 답변을 업데이트했습니다. 또한 일부 반환 초 또는 밀리 초로 날짜 형식이 일치하지 않으므로 두 가지 형식 대안을 제공했습니다.
단순화 된 에이전트 클래스를 사용하는 예제 코드를 참조하십시오.
String jsonResponse = "[\n" +
" {\n" +
" \"DateTime\":\"2021-01-27 09:18:00\",\n" +
" \"Sim_StartDateTime\":\"2019-01-01 00:00:00\",\n" +
" \"LastAgentStrategyRun\":\"2020-12-19 17:40:30.531000\"\n" +
" }\n" +
']';
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json, type, jsonDeserializationContext) -> {
try{
return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} catch (DateTimeParseException e){
return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"));
}
}).create();
Type listType = new TypeToken<ArrayList<Agent>>() {}.getType();
ArrayList<Agent> agentList = gson.fromJson(jsonResponse, listType);
System.out.println(agentList);
및 에이전트 클래스
public class Agent {
private LocalDateTime DateTime;
private LocalDateTime Sim_StartDateTime;
private LocalDateTime LastAgentStrategyRun;
public LocalDateTime getDateTime() {
return DateTime;
}
public void setDateTime(LocalDateTime dateTime) {
DateTime = dateTime;
}
public LocalDateTime getSim_StartDateTime() {
return Sim_StartDateTime;
}
public void setSim_StartDateTime(LocalDateTime sim_StartDateTime) {
Sim_StartDateTime = sim_StartDateTime;
}
public LocalDateTime getLastAgentStrategyRun() {
return LastAgentStrategyRun;
}
public void setLastAgentStrategyRun(LocalDateTime lastAgentStrategyRun) {
LastAgentStrategyRun = lastAgentStrategyRun;
}
@Override
public String toString() {
return "Agent{" +
"DateTime=" + DateTime +
", Sim_StartDateTime=" + Sim_StartDateTime +
", LastAgentStrategyRun=" + LastAgentStrategyRun +
'}';
}
}
및 출력
[Agent{DateTime=2021-01-27T09:18, Sim_StartDateTime=2019-01-01T00:00, LastAgentStrategyRun=2020-12-19T17:40:30.531}]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다