-1

I'm receiving the date in the format from the server is yyyyMMdd HH:mm:ss and I need to convert to the date format yyyy-MMM-dd HH:mm:ss using Gson JsonDeserializer.

Example:

Received date from server: 20230320 16:09:05

to be converted to: 2023-Mar-20 16:09:05

I want to convert JSON to Java using Gson API

JSON

{"service": 2,"userIP": "10.1.1.2.3","startDateTime": "20230321 12:55:44"}

Java class

public class TestJava 
{ 
    private Long service;
    private String userIP;
    private LocalDateTime startDateTime;
    //setter and getter
}

Expected output as below

TestJava [service=2, userIP=10.1.1.2.3, startDateTime=2023-Mar-21 12:55:44]
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
Purushothama
  • 89
  • 1
  • 8
  • 2
    A date in java has no format. Please share the related code! – Jens Mar 22 '23 at 06:47
  • 1
    I m not sure whats in your mind, but I dont think a JSON parser can convert date formats. You are looking for java.time library – experiment unit 1998X Mar 22 '23 at 07:04
  • @experimentunit1998X question updated ,please check – Purushothama Mar 22 '23 at 07:37
  • Seems related: [Java 8 LocalDateTime deserialized using Gson](https://stackoverflow.com/questions/22310143/java-8-localdatetime-deserialized-using-gson) Did you search? What did you find? – Ole V.V. Mar 22 '23 at 07:54
  • A `LocalDateTime` does not have a format (its `toString()` will always use the ISO-8601 format. If you want to show a different format, you'll need to format it explicitly. Where are you having problems, converting from JSON, or displaying the `LocalDateTime`? – Mark Rotteveel Mar 23 '23 at 11:15

1 Answers1

1

If you want to read and output json.

Define a custom deserialiser as follows:

class LocalDateTimeDeserializer implements JsonDeserializer < LocalDateTime > {
    @Override
    public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
    throws JsonParseException {
        return LocalDateTime.parse(json.getAsString(), 
            DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss").withLocale(Locale.ENGLISH));
    }
}

Define a custom serialiser as follows;

class LocalDateTimeSerializer implements JsonSerializer < LocalDateTime > { 
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");

    @Override
    public JsonElement serialize(LocalDateTime localDateTime, Type srcType, JsonSerializationContext context) {
        return new JsonPrimitive(formatter.format(localDateTime));
    }
}

String them together like this (for calling from static main):

private static Gson buildGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer());
    gsonBuilder.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeDeserializer());

    Gson gson = gsonBuilder.setPrettyPrinting().create();
    return gson;
}

Improve the definition of TestJava.toString() like this:

@Override
public String toString() {
    return "TestJava [service=" + service + ", userIP=" + userIP + ", startDateTime=" + formatter.format(startDateTime) + "]";
}

private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss");

Use it like this:

public static void main(String[] args) {

    Gson gson = buildGson();
    
    String inputValue = "{\"service\": 2,\"userIP\": \"10.1.1.2.3\",\"startDateTime\": \"20230321 12:55:44\"}";
    
    TestJava object = gson.fromJson(inputValue, TestJava.class);
    
    String outputValue = gson.toJson(object);
    
    System.out.println("Serialised: " + outputValue);
    
    System.out.println("toString: " + object);

}

Output:

Serialised: {
  "service": 2,
  "userIP": "10.1.1.2.3",
  "startDateTime": "2023-Mar-21 12:55:44"
}
toString: TestJava [service=2, userIP=10.1.1.2.3, startDateTime=2023-Mar-21 12:55:44]
John Williams
  • 4,252
  • 2
  • 9
  • 18
  • The formatting of the `LocalDateTime` can be put in the `toString` method and/or other methods of the enclosing class (`TestJava` in the question) is desired (typically it would not be the most important part). – Ole V.V. Mar 22 '23 at 08:15
  • Your deserializer didn’t work for me. I got *com.google.gson.JsonIOException: Failed making field 'java.time.LocalDateTime#date' accessible; either increase its visibility or write a custom TypeAdapter for its declaring type.* – Ole V.V. Mar 22 '23 at 10:11
  • 1
    deserializer didn’t work for me to – Purushothama Mar 22 '23 at 10:30
  • The way I read [the docs](https://www.javadoc.io/static/com.google.code.gson/gson/2.8.5/com/google/gson/GsonBuilder.html#setDateFormat-java.lang.String-) `setDateFormat()` only affected serialization and deserialization of `Date` objects back when we used those a decade ago. You probably need to register a type adapter. – Ole V.V. Mar 22 '23 at 10:41
  • @OleV.V. I have corrected/rewritten my answer. – John Williams Mar 22 '23 at 13:12
  • @OleV.V. LocalDateTime object does not have a format. – John Williams Mar 22 '23 at 15:15
  • Very true. [Jens said that in a comment already.](https://stackoverflow.com/questions/75808978/gson-date-conversion/75809662?noredirect=1#comment133725405_75808978) It’s unclear to me whether the OP falsely thought it could have or they wanted string output in the mentioned format. Or maybe it didn’t matter at all. – Ole V.V. Mar 22 '23 at 15:33
  • I get `toString: TestJava [service=2, userIP=10.1.1.2.3, startDateTime=2023-mar.-21 12:55:44`. One will probably want to specify locale on the formatters. Otherwise your solution works the way you describe. +1 – Ole V.V. Mar 22 '23 at 17:49