Skip to content

Commit

Permalink
Fix DateTimeParseException
Browse files Browse the repository at this point in the history
Fixes openhab#16082

Signed-off-by: Jacob Laursen <jacob-github@vindvejr.dk>
  • Loading branch information
jlaur committed Dec 20, 2023
1 parent 3e7162d commit a350723
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import java.lang.reflect.Type;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -76,6 +77,11 @@ public JsonElement serialize(ZonedDateTime src, Type typeOfSrc, JsonSerializatio
@Override
public @Nullable ZonedDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return ZONED_FORMATTER.parse(json.getAsString(), ZonedDateTime::from);
String content = json.getAsString();
try {
return ZonedDateTime.parse(content);
} catch (DateTimeParseException e) {
throw new JsonParseException("Could not parse as ZonedDateTime: " + content, e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@

import static org.junit.jupiter.api.Assertions.*;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.binding.surepetcare.internal.SurePetcareConstants;
Expand Down Expand Up @@ -78,4 +81,49 @@ public void testGetUserNull() {
fail("GSON returned null");
}
}

@Test
public void testDateFormats() {
String testResponse = """
{
"devices": [],
"households": [
{
"id": 0,
"name": "***",
"share_code": "***",
"created_user_id": 0,
"timezone_id": 374,
"version": "MTE=",
"created_at": "2021-04-24T11:41:15+00:00",
"updated_at": "2023-12-16T21:08:19.637892+00:00",
"invites": [],
"users": [],
"timezone": {
"id": 374,
"name": "(UTC+02:00) Europe/Zurich",
"timezone": "Europe/Zurich",
"utc_offset": 7200,
"created_at": "2017-08-03T08:35:34+00:00",
"updated_at": "2017-08-03T08:37:15+00:00"
}
}
],
"pets": [],
"photos": [],
"tags": [],
"user": {}
}
""";

SurePetcareTopology response = SurePetcareConstants.GSON.fromJson(testResponse, SurePetcareTopology.class);

assertNotNull(response);
assertNotNull(response.households);
assertEquals(1, response.households.size());
assertEquals(ZonedDateTime.of(2021, 4, 24, 11, 41, 15, 0, ZoneOffset.UTC),
response.households.get(0).createdAt);
assertEquals(ZonedDateTime.of(2023, 12, 16, 21, 8, 19, 637892000, ZoneOffset.UTC),
response.households.get(0).updatedAt);
}
}

0 comments on commit a350723

Please sign in to comment.