How to convert a java object to simple json string without converting the LocalDateTime field to an extended json object?

huangapple go评论79阅读模式
英文:

How to convert a java object to simple json string without converting the LocalDateTime field to an extended json object?

问题

我需要帮助将一个 Java 对象转换为 JSON 字符串但不希望将 LocalDateTime 字段转换为单独的对象

class MyObj {
    LocalDateTime date;
}

然后

MyObj dateObj = new MyObj();
dateObj.date = LocalDateTime.now();

当我将其转换为 JSON 时

Gson gson = new GsonBuilder().setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();
gson.toJson(dateObj);

我得到的是这样的

{
    "date": {
        "date": {
            "year": 2020,
            "month": 8,
            "day": 27
        },
        "time": {
            "hour": 8,
            "minute": 59,
            "second": 47,
            "nano": 0
        }
    }
}

但我想要的是

"date": "2020-08-27T08:59:47.0Z"

请帮我解决这个问题
英文:

I need a help to convert a java object to json string without converting a LocalDateTime field to a separate object.

class MyObj {
 LocalDateTime date;
}

then,

MyObj dateObj = new MyObj();
dateObj.date = LocalDateTime.now();  

When I am converting it to a json,

Gson gson = new GsonBuilder().setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();
gson.toJson(dateObj);

I am getting this:

 {
  "date": {
    "date": {
      "year": 2020,
      "month": 8,
      "day": 27
    },
    "time": {
      "hour": 8,
      "minute": 59,
      "second": 47,
      "nano": 0
    }
  }
}

But I want this:

"date" : "2020-08-27T08:59:470Z"

Kindly help me about it.

答案1

得分: 1

我通过以下方式解决了。

创建一个 Gson 对象:

Gson gson = new GsonBuilder()
            .setPrettyPrinting()
            .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
            .create();

使用如下方法:

String jsonRequestString = gson.toJson(request);

创建一个序列化器:

class LocalDateAdapter implements JsonSerializer<LocalDate> {

    @Override
    public JsonElement serialize(LocalDate date, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
    }
}
英文:

I solved by this way.

Create a Gson object:

Gson gson = new GsonBuilder()
	        .setPrettyPrinting()
	        .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
	        .create();

Use method like this:

String jsonRequestString = gson.toJson(request);

Create a serializer:

class LocalDateAdapter implements JsonSerializer&lt;LocalDate&gt; {

@Override
public JsonElement serialize(LocalDate date, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) {
	return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
}

答案2

得分: 0

根据setDateFormatjavadoc

> <p>日期格式将用于序列化和反序列化{@link java.util.Date}、{@link java.sql.Timestamp}和{@link java.sql.Date}。

您需要为LocalDateTime.class注册自定义序列化程序

JsonSerializer&lt;LocalDateTime&gt; localDateTimeSerializer = (src, type, context) -&gt; {
    String date = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss&quot;).format(src);
    // String date = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(src);
    // String date = src.toString();
    return new JsonPrimitive(date);
};

Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, localDateTimeSerializer).create();
gson.toJson(dateObj);

注意: LocalDateTime不存储时区信息,因此在日期格式模式中实际上不能使用**Z**。

英文:

As per javadoc of setDateFormat

> <p>The date format will be used to serialize and deserialize {@link java.util.Date}, {@link java.sql.Timestamp} and {@link java.sql.Date}.

You need to register custom serializer for LocalDateTime.class

JsonSerializer&lt;LocalDateTime&gt; localDateTimeSerializer = (src, type, context) -&gt; {
    String date = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss&quot;).format(src);
    // String date = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(src);
    // String date = src.toString();
    return new JsonPrimitive(date);
};

Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, localDateTimeSerializer).create();
gson.toJson(dateObj);

Note: LocalDateTime doesn't store timezone information, so you can't actually use Z in your date format pattern.

huangapple
  • 本文由 发表于 2020年8月27日 21:09:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63616722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定