将json响应中的null替换为空白,然后再次将其转换为json

时间:2018-06-26 12:48:14

标签: java json spring-mvc spring-boot

**输出: ========== >>>>

"status": "success",
"messages": {
    "01010000": "Data available"
},
 "data": {
   "result": [
      {
        "issuerName": "AXIS BANK LIMITED",
        "totalIssuerLimit": "55,000,000,000.00",
        "issuerLimitUtilised": "0",
        "issuerLimitAvailable": "55,000,000,000.00",
        "issue": "INE238A08302",
        "totalIssueLimit": "2,000,000,000.00",
        "issueLimitUtilised": "0",
        "issueLimitAvailable": "2,000,000,000.00"
       },
      {
          "issuerName": null,
          "totalIssuerLimit": null,
          "issuerLimitUtilised": null,
          "issuerLimitAvailable": null,
          "issue": "INE238A08344",
          "totalIssueLimit": "50,000,000,000.00",
          "issueLimitUtilised": "0",
          "issueLimitAvailable": "50,000,000,000.00"
    },**

在json响应中将null替换为空,然后再次在json中转换

public Response limitAvailability(String dataTransportFormat) throws Exception {
    logger.info("limitAvailability service");
    logger.info("dataTransportFormat: " + dataTransportFormat);

    Response response = null;
    try {
        Map<String, Object> uriVariables = new HashMap<>();
        uriVariables.put("dataTransportFormat", dataTransportFormat);


        /* System.out.println("url"+webServiceProperties.getUrls().get(MARGINS_TPR) + URL_SEGMENTS_SEPARATOR
            + webServiceProperties.getEndpoints().get(COLLATERAL_DETAILS)); */
        response = genericRestConsumer.exchange(
            webServiceProperties.getUrls().get(MARGINS_TPR) + URL_SEGMENTS_SEPARATOR
                            + webServiceProperties.getEndpoints().get(LIMIT_AVAILABILITY),
                    HttpMethod.GET, uriVariables);
        System.out.println("response-----------"+response);
        System.out.println("uriVariables-----------"+uriVariables);

        logger.info("limitAvailability data response: " + response);
    } catch (Exception e) {
        logger.error("Exception", e);
        throw e;
    }

    return response;
}

1 个答案:

答案 0 :(得分:0)

只需在控制器中创建一个方法,然后将所有null替换为空字符串即可(例如,此处的Person类)

@Override
public void serialize(Person value, JsonGenerator jgen, SerializerProvider provider) 
  throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeStringField("name", value.name);
        if (value.first == null) {
            jgen.writeStringField("first", ""); 
        }else{
            jgen.writeStringField("first", value.first);
        }
        if(value.last == null){
            jgen.writeStringField("last", "");
        }else{
            jgen.writeStringField("last", value.last);
        }
        jgen.writeEndObject();
    }
}

然后在您的实体类上

@JsonSerialize(using = PersonSerializer.class)
public class Person {
    //First/Last name etc
}