如何将长整型的 epoch 日期格式序列化为日期,使用 JSONObject。

huangapple 未分类评论48阅读模式
英文:

How to serialize Long epoch date format into date using JSONObject

问题

I have a JSON string payload containing a date in epoch (long) format. However, I need to convert it into the yyyyMMddHHmmss format. I am using custom serializers where I can apply this transformation to a particular field. However, the serialization is not being applied to that field.

**Test.java**

private static String json = "{
    "dcCountryCode": "US",
    "orderDate": 1517855400000
}";

@JsonSerialize(using = CustomLongSerializer.class)
private static Long date;

public static void main(String[] args) {
    JSONObject obj = new JSONObject(json);
    String country = obj.getString("dcCountryCode");
    date = obj.getLong("orderDate");
    System.out.println(country);
    System.out.println(date);
}

**CustomLongSerializer.java**

package com.company;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.text.SimpleDateFormat;

// This is a custom date serializer
public class CustomLongSerializer extends StdSerializer<Long> {

    protected CustomLongSerializer(Class<Long> t) {
        super(t);
    }

    protected CustomLongSerializer() {
        this(Long.class);
    }

    private static final long serialVersionUID = 1L;

    @Override
    public void serialize(Long value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        gen.writeString(df.format(value));
    }
}

Expected output in yyyyMMddHHmmss format.

However, it is still returning the epoch date format.

Can anyone help me with this.
英文:

I have json string payload having date in epoch (long) format.But I have to convert that into yyyyMMddHHmmss format.I'm using custom serializers where I can apply that on particular field.But the serialization is not able to apply on that field.

Test.java

 private static String json = &quot;{
         
          &quot;dcCountryCode&quot;: &quot;US&quot;,
          &quot;orderDate&quot;: 1517855400000
        }&quot;;



    @JsonSerialize(using = CustomLongSerializer.class)
    private static Long date;

    public static void main(String[] args) {

     
        JSONObject obj = new JSONObject(json);

        String country = obj.getString(&quot;dcCountryCode&quot;);

        date = obj.getLong(&quot;orderDate&quot;);

        
        System.out.println(country);
        
        System.out.println(date);

    }

CustomLongSerializer.java


    package com.company;
    
    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.databind.SerializerProvider;
    import com.fasterxml.jackson.databind.ser.std.StdSerializer;
    
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    
    
    // This is for Custom Date serializer
    public class CustomLongSerializer extends StdSerializer&lt;Long&gt; {
    
        protected CustomLongSerializer(Class&lt;Long&gt; t) {
            super(t);
        }
    
        protected CustomLongSerializer() {
            this(Long.class);
        }
    
        private static final long serialVersionUID = 1L;
    
        @Override
        public void serialize(Long value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    
            SimpleDateFormat df = new SimpleDateFormat(&quot;yyyyMMddHHmmss&quot;);
            gen.writeString(df.format(value));
    
        }
    
    }



Expected Out put in yyyyMMddHHmmss format.

But still returning epoch date format.

Can anyone help me with this.


</details>


# 答案1
**得分**: 0

以下是您要翻译的内容:

可能通过禁用 `SerializationFeature.WRITE_DATES_AS_TIMESTAMPS` 并在映射器中设置日期格式化程序来以更简单的方式实现:

```java
public class TestDate {
    private String dcCountryCode;
    private Date date;
    // 获取器/设置器
}

// 测试类
String json = "{\"dcCountryCode\": \"US\",\"date\": 1517855400000}";

ObjectMapper mapper = new ObjectMapper()
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .setDateFormat(new SimpleDateFormat("yyyyMMddHHmmss"));

TestDate test = mapper.readValue(json, TestDate.class);

System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(test));

输出结果:

{
  "dcCountryCode" : "US",
  "date" : "20180205203000"
}
英文:

It may be implemented in a simpler way by disabling SerializationFeature.WRITE_DATES_AS_TIMESTAMPS and setting DateFormatter in the mapper:

public class TestDate {
    private String dcCountryCode;
    private Date date;
// getters/setters
}

// test class
String json = &quot;{\n&quot; +
&quot;          \&quot;dcCountryCode\&quot;: \&quot;US\&quot;,\n&quot; +
&quot;          \&quot;date\&quot;: 1517855400000\n&quot; +
&quot;        }&quot;;

ObjectMapper mapper = new ObjectMapper()
                .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .setDateFormat(new SimpleDateFormat(&quot;yyyyMMddHHmmss&quot;));

TestDate test = mapper.readValue(json, TestDate.class);

System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(test));

Output:

{
  &quot;dcCountryCode&quot; : &quot;US&quot;,
  &quot;date&quot; : &quot;20180205203000&quot;
}

huangapple
  • 本文由 发表于 2020年5月5日 00:18:06
  • 转载请务必保留本文链接:https://java.coder-hub.com/61596811.html
匿名

发表评论

匿名网友

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

确定