从json中读取日期作为数组整数,并使用POJO映射为整数 [英] Read date as an array integer from json and map with POJO as an integer

查看:62
本文介绍了从json中读取日期作为数组整数,并使用POJO映射为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从rest api获取json,我想将数据存储在POJO列表中.下面是相同的代码:

I'm getting json from rest api and I want to store the data in list of POJO. Below is the codefor the same:

public List<myObject> mapper(){

    String myObjectData= restClient.getAllOriginal("myObject");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

    
    List<CommitmentPojo> resultDto = null;

    try
    {

        Map<String, List<MyObject>> root = mapper.readValue(jsonString, new TypeReference<Map<String, List<MyObject>>>() {});
        List<MyObject> objects = root.get("myObject");
        
    }
    catch (JsonParseException e)
    {
        e.printStackTrace();
    }
    catch (JsonMappingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return resultDto;
}

从rest api获取字符串的方法:

Method which gets the string from rest api:

public  String getAllOriginal(String resourcePath) {
       // Objects.requireNonNull(this.baseUri, "target cannot be null");
        return this.client
                .target("http://comtsrvc.ny.qa.flx.nimbus.gs.com:3802/v2/")
                .path(resourcePath)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .cookie("mySSO", getCookie())
                .get()
                .readEntity(String.class);
    }

下面是我的json:

{
  
  "myObject" : [ {
    "key" : {
      "srcSys" : "REPO_1",
      "srcSysRef" : "20200909_1911_1"
    },
    "productData" : {
      "id" : null,
      "number" : null,
      "isn" : null,
      "productId" : null,
      "productAdditionalData" : {
        "assetClassTree" : "UNCLASSIFIED",
        "description" : "UNCLASSIFIED",
        "productTypeData" : {
          "productType" : "UNCLASSIFIED",
          "productGroup" : "UNCLASSIFIED"
        }
      }
    },
    "state" : "OPEN",
    "type" : "01"
  }, {
    "key" : {
      "srcSys" : "REPO_2",
      "srcSysRef" : "20200403_3892_1"
    },
    "productData" : {
      "id" : "1",
      "number" : "11",
      "isn" : "null",
      "productId" : 1234,
      "productAdditionalData" : {
        "assetClassTree" : "xyz",
        "description" : "abc",
        "productTypeData" : {
          "productType" : "UNCLASSIFIED",
          "productGroup" : "UNCLASSIFIED"
        }
      }
    },
    "state" : "OPEN",
    "startDate" : [2020, 9, 22],
    "endDate" : [2020, 9, 24],
    "tradAcctType" : "01"
  } ]
  }

提供了我不能修改现有POJO(除非直到需要)的原因,因为它需要大量修改. 我很困惑如何从数组访问日期并将其映射到startDate具有整数数据类型的POJO.

Provided that I cannot modify the existing POJO(unless and until required) as it will need a lot of modifications. I'm confused how to access date from the array and map it to POJO where startDate has integer data type.

推荐答案

是否可以在POJO中定义以@JsonCreator注释的构造函数,然后解析json中日期字段的列表?

Is it possible for you to define a constructor annotated with @JsonCreator in POJO and then parse the List for date fields in json?

与此类似.

Test.java

Test.java

import java.util.List;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class Test {
    private String state;
    private int startDate;
    private int endDate;

    @JsonCreator
    public Test(@JsonProperty("startDate") List<Integer> startDate,
            @JsonProperty("endDate") List<Integer> endDate) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Integer value : startDate) {
            stringBuilder.append(value);
        }
        this.startDate = Integer.parseInt(stringBuilder.toString());
        stringBuilder.setLength(0);
        for (Integer value : endDate) {
            stringBuilder.append(value);
        }
        this.endDate = Integer.parseInt(stringBuilder.toString());
    }

    /**
     * @return the state
     */
    public String getState() {
        return state;
    }

    /**
     * @param state
     *            the state to set
     */
    public void setState(String state) {
        this.state = state;
    }

    /**
     * @return the startDate
     */
    public int getStartDate() {
        return startDate;
    }

    /**
     * @param startDate
     *            the startDate to set
     */
    public void setStartDate(int startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the endDate
     */
    public int getEndDate() {
        return endDate;
    }

    /**
     * @param endDate
     *            the endDate to set
     */
    public void setEndDate(int endDate) {
        this.endDate = endDate;
    }
}

Main.java

Main.java

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) {
        String json = "{\"state\" : \"OPEN\", \"startDate\" : [2020, 9, 22], \"endDate\" : [2020, 9, 24]}";

        ObjectMapper mapper = new ObjectMapper();
        try {
            Test test = mapper.readValue(json, Test.class);
            System.out.println(test.getStartDate() + "   " + test.getEndDate()
                    + "   " + test.getState());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

输出:

2020922   2020924   OPEN

如果无法更新POJO类,则可以使用另一种替代方法来实现自定义解串器.您可以在其中实现类似的转换逻辑.

If POJO class update is not possible then there is another alternative way to implement a custom deserializer. Where you can implement similar conversion logic.

CustomTest.java

CustomTest.java

public class CustomTest {
    private String state;
    private int startDate;
    private int endDate;

    /**
     * @return the state
     */
    public String getState() {
        return state;
    }

    /**
     * @param state
     *            the state to set
     */
    public void setState(String state) {
        this.state = state;
    }

    /**
     * @return the startDate
     */
    public int getStartDate() {
        return startDate;
    }

    /**
     * @param startDate
     *            the startDate to set
     */
    public void setStartDate(int startDate) {
        this.startDate = startDate;
    }

    /**
     * @return the endDate
     */
    public int getEndDate() {
        return endDate;
    }

    /**
     * @param endDate
     *            the endDate to set
     */
    public void setEndDate(int endDate) {
        this.endDate = endDate;
    }
}

CustomTestDeserializer.java

CustomTestDeserializer.java

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

public class CustomTestDeserializer extends StdDeserializer<CustomTest> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public CustomTestDeserializer() {
        this(null);
    }

    protected CustomTestDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public CustomTest deserialize(JsonParser jp, DeserializationContext dCtxt)
            throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        String state = node.get("state").asText();
        ObjectMapper mapper = new ObjectMapper();
        List<Integer> startDateValue = mapper.convertValue(
                node.get("startDate"), List.class);
        StringBuilder stringBuilder = new StringBuilder();
        for (Integer value : startDateValue) {
            stringBuilder.append(value);
        }
        int startDate = Integer.parseInt(stringBuilder.toString());

        List<Integer> endDateValue = mapper.convertValue(node.get("endDate"),
                List.class);
        stringBuilder.setLength(0);
        for (Integer value : endDateValue) {
            stringBuilder.append(value);
        }
        int endDate = Integer.parseInt(stringBuilder.toString());

        CustomTest customTest = new CustomTest();
        customTest.setEndDate(endDate);
        customTest.setStartDate(startDate);
        customTest.setState(state);
        return customTest;
    }
}

CustomTestClient.java

CustomTestClient.java

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

public class CustomTestClient {
    public static void main(String[] args) {
        String json = "{\"state\" : \"OPEN\", \"startDate\" : [2020, 9, 22], \"endDate\" : [2020, 9, 24]}";

        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addDeserializer(CustomTest.class, new CustomTestDeserializer());
        mapper.registerModule(module);

        try {
            CustomTest customTest = mapper.readValue(json, CustomTest.class);
            System.out.println(customTest.getStartDate() + "   "
                    + customTest.getEndDate() + "   " + customTest.getState());
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}

输出:

2020922   2020924   OPEN

注意:请记住要正确实现null处理.

NOTE: Please remember to implement null handling properly.

假设您不想更改POJO,因此需要在客户端代码上注册此自定义反序列化器,而不是在bean类级别使用@JsonDeserialize注释.

Assuming you don't want to change the POJO hence instead of @JsonDeserialize annotation at bean class level, need to register this custom deserializer at client code.

这篇关于从json中读取日期作为数组整数,并使用POJO映射为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆