내 자바 프로젝트에는 다음 오류가 발생하는 gson deserializer 함수가 있습니다.
java.lang.NumberFormatException: For input string: "2017-01-28 13:28:20"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
at com.google.gson.JsonPrimitive.getAsLong(JsonPrimitive.java:238)
at com.example.myproject.controller.MyController$1.deserialize(MyController.java:222)
at com.example.myproject.controller.MyController$1.deserialize(MyController.java:1)
at com.google.gson.TreeTypeAdapter.read(TreeTypeAdapter.java:58)
at com.google.gson.internal.bind.TypeAdapters$22$1.read(TypeAdapters.java:526)
at com.google.gson.internal.bind.TypeAdapters$22$1.read(TypeAdapters.java:524)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
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.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:768)
at com.google.gson.Gson.fromJson(Gson.java:717)
at com.google.gson.Gson.fromJson(Gson.java:689)
아래 json 문자열을 역 직렬화 할 때이 오류가 발생합니다.
jsonString = {"repList":[{"createdOn":"2017-01-28 13:28:20","date":"2016-11-17 00:00:00","description":"","id":45,"userId":10}],"subList":[{"attachmentCount":0,"dateOn":"2017-01-28 13:28:20","id":86,"screenId":1,"sync":"1","repId":45,"userId":10}]}
아래는 gson deserialization을 수행 한 내 기능입니다.
SimpleDateFormat dtf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ENGLISH);
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement json, Type type, JsonDeserializationContext deserializationContext) throws JsonParseException {
String frStr = dtf.format(new Date(json.getAsJsonPrimitive().getAsLong()));
dtf.setTimeZone(TimeZone.getDefault());
Date retDate =null;
try {
retDate = dtf.parse(frStr);
} catch (ParseException e) {
e.printStackTrace();
}
return retDate;
}
});
gson = builder.create();
MainAccounts mainAcc = gson.fromJson(jsonString, MainAccounts.class);
내가 주목 한 것은 json 프리미티브를 아래와 같이 변환 할 때 예외가 발생한다는 것입니다.
json.getAsJsonPrimitive().getAsLong()
deserialize 메서드 내부에서이 문제를 어떻게 해결할 수 있습니까? 제발 도와주세요.
당신은 직접의 가치를 얻을 필요 JsonElement
가 정말 같이 A가 String
아닌 long
메소드를 호출하여 getAsString()
, 그렇지 않으면 당신이 얻을 것이다 NumberFormatException
당신은, 그래서 발견했습니다 이미로 JsonDeserializer
대신해야한다 :
new JsonDeserializer<Date>() {
private SimpleDateFormat dtf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
{
// Indicate the time zone of the input date
dtf.setTimeZone(TimeZone.getTimeZone("Asia/Dubai"));
}
@Override
public Date deserialize(JsonElement json, Type type,
JsonDeserializationContext deserializationContext) throws JsonParseException {
try {
// Get the json element as a String and parse it to get a Date
return dtf.parse(json.getAsString());
} catch (ParseException e) {
// Throw a JsonParseException in case of a parsing error
throw new JsonParseException(e);
}
}
}
NB : 그대로, JsonDeserializer
위에서 제안한 익명의 내부 클래스는 스레드로부터 안전하지 않습니다. SimpleDateFormat
그 이유는 스레드로부터 안전하지 않기 때문에 스레드로부터 안전하지 않으므로 인스턴스를 공유하지 말고 JSON 콘텐츠를 역 직렬화하고 싶을 때마다 새 인스턴스를 만드십시오.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다